Python 在熊猫中将字符串转换为小写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42750551/
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-08-19 22:06:40  来源:igfitidea点击:

Converting strings to a lower case in pandas

pythonstringpandaslowercase

提问by Feyzi Bagirov

I have a data that contains domain names:

我有一个包含域名的数据:

 url          var1
www.CNN.com   xsd
www.Nbc.com   wer
www.BBc.com   xyz
www.fOX.com   zyx
....

The data is of the Series type. I am using the following to convert url variable to lower case:

数据属于系列类型。我正在使用以下内容将 url 变量转换为小写:

df.apply(lambda x: x.astype(str).str.lower())

However, they remain the same.

但是,它们保持不变。

What am I doing wrong?

我究竟做错了什么?

回答by David

df['url'] = df['url'].str.lower()

should operate on the series and replace it with the lower case version.

应该在系列上运行并将其替换为小写版本。

回答by Vivek Ananthan

To convert a single column we can use,

要转换我们可以使用的单个列,

df.column_name.str.lower()

or

或者

df['column_name'].str.lower()

Hope this helps !

希望这可以帮助 !

回答by jezrael

I think you need assign output back, better is omit applyif works only with column url:

我认为您需要重新分配输出,apply如果仅适用于列,则最好省略url

df = pd.DataFrame({'url': ['www.CNN.com', 'www.Nbc.com', 'www.BBc.com', 'www.fOX.com'], 
                   'var1': ['XSD', 'wer', 'xyz', 'zyx']})

print (df)
           url var1
0  www.CNN.com  XSD
1  www.Nbc.com  wer
2  www.BBc.com  xyz
3  www.fOX.com  zyx

#if types of column is str, astype is not necessary
df.url = df.url.astype(str).str.lower()
print (df)
           url var1
0  www.cnn.com  XSD
1  www.nbc.com  wer
2  www.bbc.com  xyz
3  www.fox.com  zyx

But if need convert all columns of dfto lowercase strings:

但如果需要将所有列转换dflowercase strings:

df = df.astype(str).apply(lambda x: x.str.lower())
print (df)
           url var1
0  www.cnn.com  xsd
1  www.nbc.com  wer
2  www.bbc.com  xyz
3  www.fox.com  zyx