Converting strings to a lower case in pandas [duplicate]

吃可爱长大的小学妹 提交于 2019-12-05 01:25:16
df['url'] = df['url'].str.lower()

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

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

To convert a single column we can use,

df.column_name.str.lower()

or

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

Hope this helps !

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