pandas的函数应用
import pandas as pd
import numpy as np
df = pd.DataFrame(np.modf(np.random.randn(5,4)*100)[1].astype('int32'),columns=list('ABCD'))
df
|
A |
B |
C |
D |
0 |
-58 |
7 |
105 |
-83 |
1 |
-191 |
34 |
-98 |
-270 |
2 |
10 |
59 |
-98 |
-210 |
3 |
89 |
-54 |
23 |
-146 |
4 |
-17 |
52 |
-153 |
95 |
1、可直接使用NumPy的函数(求绝对值 abs)
df1 = np.abs(df)
df1
|
A |
B |
C |
D |
0 |
58 |
7 |
105 |
83 |
1 |
191 |
34 |
98 |
270 |
2 |
10 |
59 |
98 |
210 |
3 |
89 |
54 |
23 |
146 |
4 |
17 |
52 |
153 |
95 |
df2 = np.sum(df1)
df2
A 365
B 206
C 477
D 804
dtype: int64
2、通过apply将函数应用到列或行上
注意轴的方向,默认axis=0.按列,
f = lambda x: x.max()
df1.apply(f)
A 191
B 59
C 153
D 270
dtype: int32
df1.apply(f,axis=1) # 按行进行对比求最大值
0 105
1 270
2 210
3 146
4 153
dtype: int32
3、通对每个数值计算用applymap
f2 = lambda x:x+100
df1.applymap(f2)
|
A |
B |
C |
D |
0 |
158 |
107 |
205 |
183 |
1 |
291 |
134 |
198 |
370 |
2 |
110 |
159 |
198 |
310 |
3 |
189 |
154 |
123 |
246 |
4 |
117 |
152 |
253 |
195 |
标签:153,函数,210,df1,270,98,应用,np,pandas
来源: https://www.cnblogs.com/gujianjian/p/15325345.html