我试图通过使用 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 个)', u'出现在索引 A')
显然这对任何推荐都不起作用?
最佳答案
是否要添加 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
关于Python 使用 lambda 将 pd.DataFrame 应用于嵌套循环是否可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19178762/