如何将函数应用于 Pandas 中的多列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50519983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:35:52  来源:igfitidea点击:

How to apply a function to multiple columns in Pandas

pandas

提问by Hannan

I have a bunch of columns which requires cleaning in Pandas. I've written a function which does that cleaning. I'm not sure how to apply the same function to many columns. Here is what I'm trying:

我有一堆需要在 Pandas 中清理的列。我写了一个函数来进行清理。我不确定如何将相同的功能应用于许多列。这是我正在尝试的:

df["Passengers", "Revenue", "Cost"].apply(convert_dash_comma_into_float)

But I'm getting KeyError.

但我收到了 KeyError。

回答by Scott Boston

Use double brackets [[]] as @chrisz points out:

使用双括号 [[]] 作为@chrisz 指出:

Here is a MVCE:

这是一个MVCE:

df = pd.DataFrame(np.arange(30).reshape(10,-1),columns=['A','B','C'])

def f(x):
    #Clean even numbers from columns.
    return x.mask(x%2==0,0)

df[['B','C']] = df[['B','C']].apply(f)
print(df)

Output

输出

    A   B   C
0   0   1   0
1   3   0   5
2   6   7   0
3   9   0  11
4  12  13   0
5  15   0  17
6  18  19   0
7  21   0  23
8  24  25   0
9  27   0  29

?