如何将函数应用于Pandas中的多个列 [英] How to apply a function to multiple columns in Pandas

查看:80
本文介绍了如何将函数应用于Pandas中的多个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

但是我收到了KeyError.

But I'm getting KeyError.

推荐答案

使用@ [z]指出的方括号[[]]:

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

这是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

​

这篇关于如何将函数应用于Pandas中的多个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆