如何通过相应索引处的参数调用 pandas 列中一行中的每个函数?



我想在 B 列中调用不同的函数,在 A 列中使用不同的行值。

我不确定如何在 pandas 中执行此操作,但我不想遍历行 - 只需组合行并获取它们各自的值 - 类似于我在下面尝试的。

这能做到吗?

请参阅下面的代码以了解我已经尝试过的内容

df = pd.DataFrame({'A': [i for i in range(160)], 'B': [lambda a: i * a for i in range(160)]})
# call each function in each row matched with the respective row in the other column
df['B'](df['A'])

我收到以下错误

TypeError                                 Traceback (most recent call last)
<timed exec> in <module>
TypeError: 'Series' object is not callable

这是一个非常奇怪的情况,但你可以这样做:

df.apply(lambda x: x['B'](x['A']), axis=1)

它基本上遍历行,只是看起来更好。输出:

0          0
1        159
2        318
3        477
4        636
...  
155    24645
156    24804
157    24963
158    25122
159    25281
Length: 160, dtype: int64

最新更新