pythonscrub1234
pythonscrub1234

Reputation: 63

How to use apply() to change data in a pandas data frame to lowercase?

I have this pandas dataframe:

         custid  age income     gen   wp   mp  lip
CustAtt                                           
0           101   45   $45K    Male   No  Yes   No
1           106   40   $39K  Female  Yes  Yes  Yes
2           111   42   $46K    Male   No   No   No
3           116   43   $36K    Male  Yes  Yes  Yes
4           121   38   $59K  Female   No  Yes  Yes
5           126   55   $28K  Female   No   No   No
6           131   35   $35K    Male   No  Yes  Yes
7           136   27   $26K    Male  Yes   No   No
8           141   43   $36K    Male   No  Yes   No
9           146   41   $38K  Female  Yes  Yes   No

And what I want to do is use apply() with a function to convert all the data to lowercase. I couldn't find anything on the internet showing how to do this, I am currently stuck with this.

def low(x):
    return x.lower()
df.apply(low)

however it gives me error that series object has no attribute lower. Any help greatly appreciated! Thanks!

Upvotes: 0

Views: 561

Answers (2)

wwnde
wwnde

Reputation: 26676

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



       custid age income     gen   wp   mp  lip
CustAtt                                         
0          101  45   $45k    male   no  yes   no
1          106  40   $39k  female  yes  yes  yes
2          111  42   $46k    male   no   no   no
3          116  43   $36k    male  yes  yes  yes
4          121  38   $59k  female   no  yes  yes
5          126  55   $28k  female   no   no   no
6          131  35   $35k    male   no  yes  yes
7          136  27   $26k    male  yes   no   no
8          141  43   $36k    male   no  yes   no
9          146  41   $38k  female  yes  yes   no

Upvotes: 2

Daisuke Akagawa
Daisuke Akagawa

Reputation: 484

That's because column custid and age have a integer values. Integer value doesn't have lower() function.

For example, if you want to change gen's data to a lower case, you can implement it like below.

df["gen"] = df["gen"].apply(low)

Upvotes: 2

Related Questions