Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lower all the elements in a pandas dataframe?

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

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:

Out[12]: 

   X  Y  Z
0  a  b  d
1  c  e  c

I look over the documentation and 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?.

like image 455
john doe Avatar asked Oct 28 '16 19:10

john doe


1 Answers

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.

like image 85
ayhan Avatar answered Sep 28 '22 03:09

ayhan