我有一个以下形式的数据框 df:
animal fruit
0 "Dog" "Apple"
1 "Cat" "Banana"
2 "Rat" "Grape"
我想将 str.lower() 应用于所有列(但不是标题)。
这有效:
for i in df:
df[i] = df[i].str.lower()
我怎样才能把它写成列表理解?
我尝试过:
df[i] = [df[i].str.lower() for i in df]
但这不起作用,我得到一个:
TypeError: list indices must be integers, not instancemethod
我必须在列表理解中更改什么才能使其工作?
其次,是否有一种更“Pandas-onicy”的方式来做到这一点,也许使用 pandas.apply() 函数?
非常感谢您的帮助。
最佳答案
列表理解的输出是Series
列表。所以需要concat
列表
:
L = [df[i].str.lower() for i in df]
print (L)
[0 dog
1 cat
2 rat
Name: animal, dtype: object, 0 apple
1 banana
2 grape
Name: fruit, dtype: object]
df1 = pd.concat(L, axis=1)
print (df1)
animal fruit
0 dog apple
1 cat banana
2 rat grape
解决方案 apply
:
print (df.apply(lambda x: x.str.lower()))
animal fruit
0 dog apple
1 cat banana
2 rat grape
时间:
df = pd.concat([df]*1000).reset_index(drop=True)
df = pd.concat([df]*1000, axis=1)
df.columns = range(len(df.columns))
#[3000 rows x 2000 columns]
print (df)
In [89]: %timeit (pd.concat([df[i].str.lower() for i in df], axis=1))
1 loop, best of 3: 2.3 s per loop
In [90]: %timeit (df.apply(lambda x: x.str.lower()))
1 loop, best of 3: 2.63 s per loop
In [91]: %timeit (df.stack().str.lower().unstack())
1 loop, best of 3: 5.04 s per loop
关于python - 通过列表理解将 str.lower 应用到 Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40907470/