【发布时间】:2015-12-11 20:54:33
【问题描述】:
假设这是我的功能:
def function(x):
return x.str.lower()
这是我的 DataFrame (df)
A B C D
0 1.67430 BAR 0.34380 FOO
1 2.16323 FOO -2.04643 BAR
2 0.19911 BAR -0.45805 FOO
3 0.91864 BAR -0.00718 BAR
4 1.33683 FOO 0.53429 FOO
5 0.97684 BAR -0.77363 BAR
我想将该函数应用于列B 和D。 (将其应用于完整的 DataFrame 不是答案,因为它会在数值列中产生 NaN 值)。
这是我的基本想法:df.apply(function, axis=1)
但我无法理解如何选择不同的列来应用该函数。我已经尝试过按数字位置、名称等进行索引的各种方式。
我花了很多时间阅读这方面的内容。这不是其中任何一个的直接副本:
How to apply a function to two columns of Pandas dataframe
Pandas: How to use apply function to multiple columns
Pandas: apply different functions to different columns
Python Pandas: Using 'apply' to apply 1 function to multiple columns
【问题讨论】:
-
尽量避免使用
apply。如果您不确定是否需要使用它,则可能不需要。我建议看看When should I ever want to use pandas apply() in my code?。