pandas 如何降低熊猫数据框中的所有元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40312128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:18:28  来源:igfitidea点击:

How to lower all the elements in a pandas dataframe?

pythonpython-3.xpandas

提问by john doe

Just a quick question guys, I have a pandas dataframe:

只是一个简单的问题,我有一个Pandas数据框:

In [11]: df = pd.DataFrame([['A', 'B'], ['C', E], ['D', 'C']],columns=['X', 'Y', 'Z'])

In [12]: df

Out[12]: 

   X  Y  Z
0  A  B  D
1  C  E  C

How can I convert to lower all the elements of df:

如何转换以降低以下所有元素df

Out[12]: 

   X  Y  Z
0  a  b  d
1  c  e  c

I look over the documentationand I tried the following:

我查看了文档并尝试了以下操作:

df = [[col.lower() for col in [df["X"],df["Y"], df["Z"]]]]
df

Nevertheless, it doesnt work. How to lower all the elements inside a pandas dataframe?.

然而,它不起作用。如何降低Pandas数据框中的所有元素?。

回答by ayhan

Either

任何一个

df.applymap(str.lower)
Out: 
   X  Y  Z
0  a  b  d
1  c  e  c

Or

或者

df.apply(lambda col: col.str.lower())
Out: 
   X  Y  Z
0  a  b  d
1  c  e  c

The first one is faster and it looks nicer but the second one can handle NaNs.

第一个更快,看起来更好,但第二个可以处理 NaN。

回答by hemraj

using applymap with lambda will work even if df contain NaN values and String

即使 df 包含 NaN 值和字符串,将 applymap 与 lambda 一起使用也能工作

import pandas as pd

df = df.applymap(lambda x: x.lower() if pd.notnull(x) else x)