【问题标题】:How to apply a function to multiple columns in Pandas [duplicate]如何将函数应用于 Pandas 中的多个列 [重复]
【发布时间】:2018-11-04 07:25:21
【问题描述】:

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

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

但是我得到了 KeyError。

【问题讨论】:

  • 不应该是df[["Passengers", "Revenue", "Cost"]]吗?索引数据框时需要使用列名列表。

标签: pandas


【解决方案1】:

@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)

输出

    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

​

【讨论】:

  • 谢谢,我列出了它,现在得到 TypeError,它无法将系列转换为 。但是当我只提供像 df["Passengers"].apply(convert_dash_comma_into_float) 这样的一列时,它显然有效
  • 这个解决方案不起作用...
  • @mathee 这似乎适用于这个例子。 B 列和 C 列都具有带零的偶数值 sub。每个函数,f。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-04
  • 2020-12-09
  • 2015-05-01
  • 1970-01-01
  • 2013-02-17
  • 1970-01-01
相关资源
最近更新 更多