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

Han*_*nan 3 pandas

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

df["Passengers", "Revenue", "Cost"].apply(convert_dash_comma_into_float)
Run Code Online (Sandbox Code Playgroud)

但我收到了 KeyError。

Sco*_*ton 7

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

这是一个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)
Run Code Online (Sandbox Code Playgroud)

输出

    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

?
Run Code Online (Sandbox Code Playgroud)