=== 聚合 apply ===
定义:apply是pandas库的一个重要函数,多和groupby函数一起使用,也可以直接用于DataFrame和Series对象。主要用于数据聚合运算,可以很方便得对分组进行现有的运算和自定义运算。
![img_35634d11df8ddaea49562ac1522d6ae6.png](https://yqfile.alicdn.com/img_35634d11df8ddaea49562ac1522d6ae6.png?x-oss-process=image/resize,w_1400/format,webp)
使用场景: 自定义函数处理数据
df1 = pd.DataFrame(np.random.randint(1,9,(4,4)),columns=list('abcd'))
df1
![img_95ee9e67ba6a7c4e45321c8a1dcee790.png](https://yqfile.alicdn.com/img_95ee9e67ba6a7c4e45321c8a1dcee790.png?x-oss-process=image/resize,w_1400/format,webp)
df1.apply(lambda x:x*10)
![img_551aebc81987234f8586d4d8615c9f61.png](https://yqfile.alicdn.com/img_551aebc81987234f8586d4d8615c9f61.png?x-oss-process=image/resize,w_1400/format,webp)
df1['a'].apply(lambda x:x*10)
0 50
1 80
2 80
3 30
Name: a, dtype: int64
df1.apply(lambda x:x*10,axis=1)
![img_16cbf3474122fe58bbfb426bd4e6500f.png](https://yqfile.alicdn.com/img_16cbf3474122fe58bbfb426bd4e6500f.png?x-oss-process=image/resize,w_1400/format,webp)
df1.loc[0:2,'a':'b'].apply(lambda x:x*10)
![img_9c028855a0f6733b1b44e2e54fc23cc0.png](https://yqfile.alicdn.com/img_9c028855a0f6733b1b44e2e54fc23cc0.png?x-oss-process=image/resize,w_1400/format,webp)
=== 自定义函数 ===
def f1(x):
print(type(x))
return x*10
df1.apply(f1)
使用自定义函数,需要明白参数的数据是什么数据类型
![img_f6643399e5c53fc20a351fdb3389503e.png](https://yqfile.alicdn.com/img_f6643399e5c53fc20a351fdb3389503e.png?x-oss-process=image/resize,w_1400/format,webp)
字符串拼接
data = np.random.randint(1,10,(3,3))
df1 = pd.DataFrame(data,columns=list('abc'))
df1
![img_64fef88b5ed777bcc36f058d3e0e6fac.png](https://yqfile.alicdn.com/img_64fef88b5ed777bcc36f058d3e0e6fac.png?x-oss-process=image/resize,w_1400/format,webp)
定义有参数的函数
def f2(x,str_text):
return str(x)+str_text
df1['a'].apply(f2,args = (' nice',)) #通过args传入参数元组
0 1 nice
1 2 nice
2 6 nice
Name: a, dtype: object