Python使用lambda来代替嵌套循环应用pd.DataFrame有可能吗?

时间:2013-10-04 10:16:25

标签: python performance nested pandas

我试图通过使用lambda apply来创建一个新列来避免python中的嵌套循环 使用以下论点:

from pandas import *
import pandas as pd    
df = pd.DataFrame((np.random.rand(100, 4)*100), columns=list('ABCD'))
df['C'] = df.apply(lambda A,B: A+B)

TypeError :('()正好接受2个参数(1个给定)',未在索引A'处发生')

显然这对任何建议都不起作用?

1 个答案:

答案 0 :(得分:10)

是否要添加列A和列B并将结果存储在C中?然后你可以更简单:

df.C = df.A + df.B

正如@EdChum在评论中指出的那样,apply中函数的参数是一个系列,默认情况下在轴0上是行(轴1表示列):

>>> df.apply(lambda s: s)[:3]
           A          B          C          D
0  57.890858  72.344298  16.348960  84.109071
1  85.534617  53.067682  95.212719  36.677814
2  23.202907   3.788458  66.717430   1.466331

在这里,我们添加第一行和第二行:

>>> df.apply(lambda s: s[0] + s[1])
A    143.425475
B    125.411981
C    111.561680
D    120.786886
dtype: float64

要处理列,请使用axis=1关键字参数:

>>> df.apply(lambda s: s[0] + s[1], axis=1)
0     130.235156
1     138.602299
2      26.991364
3     143.229523
...
98    152.640811
99     90.266934

产生与按名称引用列相同的结果:

>>> (df.apply(lambda s: s[0] + s[1], axis=1) == 
     df.apply(lambda s: s['A'] + s['B'], axis=1))
0     True
1     True
2     True
3     True
...
98    True
99    True
相关问题