首页 > 其他分享 >PyPackage01---Pandas10_apply方法使用

PyPackage01---Pandas10_apply方法使用

时间:2022-10-11 15:36:16浏览次数:78  
标签:function PyPackage01 --- test Pandas10 apply row columns axis


Intro

  R里面apply族函数很强大,原来以为python的是阉割版,没想到也很强大,还是需要多看看文档。。。
相关环境和package信息:

import sys
import pandas as pd
import numpy as np
print("Python版本:",sys.version)
print("pandas版本:",pd.__version__)
print("numpy版本:",np.__version__)
Python版本: 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)]
pandas版本: 0.23.4
numpy版本: 1.17.4

参数说明

Parameters
func:function
Function to apply to each column or row.

axis:{0 or ‘index’, 1 or ‘columns’}, default 0
Axis along which the function is applied:

  • 0 or ‘index’: apply function to each column.对每一列进行操作
  • 1 or ‘columns’: apply function to each row.对每一行进行操作,明明是columns但是却是对行操作。。。

raw:bool, default False
Determines if row or column is passed as a Series or ndarray object:

  • False : passes each row or column as a Series to the function.
  • True : the passed function will receive ndarray objects instead. If you are just applying a NumPy reduction function this will achieve much better performance.
  • 这个参数不知道啥意思,似乎不影响使用

result_type:{‘expand’, ‘reduce’, ‘broadcast’, None}, default None
These only act when axis=1 (columns):

  • ‘expand’ : list-like results will be turned into columns.
  • ‘reduce’ : returns a Series if possible rather than expanding list-like results. This is the opposite of ‘expand’.
  • ‘broadcast’ : results will be broadcast to the original shape of the DataFrame, the original index and columns will be retained.
    The default behaviour (None) depends on the return value of the applied function: list-like results will be returned as a Series of those. However if the apply function returns a Series these are expanded to columns.
    New in version 0.23.0.
    返回结果的形式,除了broadcast,其他应该类似

arg:stuple
Positional arguments to pass to func in addition to the array/series.

kwds:
Additional keyword arguments to pass as keywords arguments to func.

Returns
Series or DataFrame
Result of applying func along the given axis of the DataFrame.

对所有元素进行操作

df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B'])



A

B

0

4

9

1

4

9

2

4

9

df.apply(np.sqrt)



A

B

0

2.0

3.0

1

2.0

3.0

2

2.0

3.0

行操作

行求和

df.apply(np.sum,axis=1)
0    13
1 13
2 13
dtype: int64

取出每一行中最大的元素

df.apply(np.max,axis=1)
0    9
1 9
2 9
dtype: int64

列操作

df.apply(np.sum,axis=0,result_type="expand")
A    12
B 27
dtype: int64
df.apply(np.sum,axis=0,result_type="broadcast")



A

B

0

12

27

1

12

27

2

12

27

其他复杂操作

还有些比较复杂的操作,比如对每一行中指定的某几列数据进行操作,这时,传入function即可,举个例子:

def test_f(row):
return row["A"]+10-row["B"]
df.apply(test_f,axis=1)
0    5
1 5
2 5
dtype: int64
def test_f2(row):
return [1,2,3,4]
df.apply(test_f2,axis=1)
0    [1, 2, 3, 4]
1 [1, 2, 3, 4]
2 [1, 2, 3, 4]
dtype: object
df.apply(test_f2,axis=1,result_type="expand")



0

1

2

3

0

1

2

3

4

1

1

2

3

4

2

1

2

3

4

df.apply(test_f2,axis=1,result_type="reduce")
0    [1, 2, 3, 4]
1 [1, 2, 3, 4]
2 [1, 2, 3, 4]
dtype: object
def test_f3(row):
return [1,2]
df.apply(test_f3,axis=1,result_type="broadcast")



A

B

0

1

2

1

1

2

2

1

2

broadcast好像只能扩展同样长度的,即return的list长度=列数

Ref

​[1] https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html​​​​​

                             2020-07-08 于南京市江宁区九龙湖


标签:function,PyPackage01,---,test,Pandas10,apply,row,columns,axis
From: https://blog.51cto.com/u_15575753/5746428

相关文章

  • NaiveBayes-参数求解
    knitr::opts_chunk$set(echo=TRUE)  朴素贝叶斯直观上倒是很容易理解,无非就是求后验概率最大化,但是损失函数、参数求解都是一知半解。本文以离散型朴素贝叶斯为例,做一些......
  • el-table-column 显示两行数据,多了显示省略号,hover展示全部效果,数据不多,hover不需要展
    效果图(多出,,,hover出现全文,否则鼠标移上去没反应)  html <el-table-columnlabel="释义"prop="remark"><templateslot-scope="scope">......
  • Bitcoin-NG: A Scalable Blockchain Protocol
    Motivation由于比特币平均10分钟出一个块,每个块大小限制在1MB,所以每秒只能记录3~4个交易,导致比特币系统存在着的吞吐量低下和高延迟的问题。本文的主要目的就是通过提......
  • node后端--异步处理
    异步处理的方法获取异步方法内的数据在ES6之前,处理异步通常采用callback方法:functiongetData(callback){//setTimeout:一个异步方法setTimeout(()=>{......
  • python第十二课---
    昨日内容回顾函数参数"""短的简单的靠前长的复杂的靠后同一个形参在调用的过程中不能多次赋值"""位置参数 位置形参 函数定义阶段括号内依次填写的变量名......
  • IDEA2020增加试用期-适用于30天试用期已过
    IDEA版本:2020.1.1情况描述:之前使用的试用期30天已经到期,现在被限制每次只能使用半小时搜了好几个破解教程,但都是需要在未开启试用的情况下破解;或者是将之前的IDEA卸载,再......
  • jQuery-checkobx单选框设置选中和取消选中事件
    html代码<divclass="form-check"><inputclass="form-check-inputposition-static"type="checkbox"id="che"onclick="read()">我已阅读以上条款</div>jav......
  • 直播平台怎么搭建,SpringMVC-登录验证判断
    直播平台怎么搭建,SpringMVC-登录验证判断1.拦截器 packagecom.kuang.config;importorg.springframework.web.servlet.HandlerInterceptor;importjavax.servlet.http......
  • 实习学习--git
    head^~: http://wkevin.github.io/GitChat/gitchat.html#head和head是啥用树举例,在我看来^n是(同一高度)父叔节点间的切换,~n是沿着默认路径向前进,n默认为1gitcommit-a......
  • 4-2 Transformer
    1、Seq2seqinput是一个sequence,那output有几种可能一种是input跟output的长度一样有一种case是output一个东西我们不知道应该要output多长,由机器自己决定output的长......