Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make particular column values as upper case?

Tags:

python

If I have a dataframe like

a     b     c

bob   ram   sam
john  hp    hcl

Now how do I make a and b column values as uppercase

For single column

df['a'] = df['a'].str.upper()

For all columns

df = df.applymap(lambda s:s.upper() if type(s) == str else s)

or

df.apply(lambda x: x.str.lower() if(x.dtype == 'object') else x)

Expected output

a     b  

BOB   RAM
JOHN  HP  

How do we do it for two columns at once? Like we could do the single column one twice but looking for how to do for both columns.

like image 503
Akilesh Avatar asked Sep 08 '25 13:09

Akilesh


2 Answers

You can do as follow by filter the columns:

df[['a', 'b']] = df[['a', 'b']].applymap(lambda s:s.upper())

Output:

      a    b    c
0   BOB  RAM  sam
1  JOHN   HP  hcl
like image 145
Antoine Dubuis Avatar answered Sep 10 '25 04:09

Antoine Dubuis


Use:

df[['a','b']] = df[['a','b']].applymap(lambda s: s.upper() if isinstance(s, str) else s)

Output:

      a    b    c
0   BOB  RAM  sam
1  JOHN   HP  hcl

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!