问题
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 string
s:
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