Converting strings to a lower case in pandas [duplicate]

别来无恙 提交于 2019-12-10 01:09:02

问题


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:

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

However, they remain the same.

What am I doing wrong?


回答1:


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

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




回答2:


I think you need assign output back, better is omit apply if works only with column 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 df to lowercase 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



回答3:


To convert a single column we can use,

df.column_name.str.lower()

or

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

Hope this helps !



来源:https://stackoverflow.com/questions/42750551/converting-strings-to-a-lower-case-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!