我有很多需要在Pandas中清洗的列。我编写了一个可以进行清洗的函数,但是我不知道如何将同一函数应用于多个列。以下是我的尝试:
df["Passengers", "Revenue", "Cost"].apply(convert_dash_comma_into_float)
但是我遇到了KeyError错误。
我有很多需要在Pandas中清洗的列。我编写了一个可以进行清洗的函数,但是我不知道如何将同一函数应用于多个列。以下是我的尝试:
df["Passengers", "Revenue", "Cost"].apply(convert_dash_comma_into_float)
但是我遇到了KeyError错误。
如@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
df[["Passengers", "Revenue", "Cost"]]
吧?当你索引数据框时,需要使用列名列表。 - user3483203