How to make particular column values as upper case?

Viewed 73

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.

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

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
Related