Removing lower case letter in column of Pandas dataframe

Viewed 869

I have the following df

data = {'Name':['TOMy', 'NICKs', 'KRISHqws', 'JACKdpo'], 'Age':[20, 21, 19, 18]}

How can I remove lowercase letters from the Name column such that when looking at data['Name'], I have TOM,NICK,KRISH,JACK.

I tried the following but no luck,

data['Name'].mask(data['Name'].str.match(r'^[a-z]+$'))
data['Name'] = data['Name'].str.translate(None,string.ascii_lowercase)
2 Answers

You can update the name column by making use of .str.replace(..) [pandas-doc]:

df['Name'] = df['Name'].str.replace('[a-z]', '')

For the given sample data, this gives us:

>>> df['Name'].str.replace('[a-z]', '')
0      TOM
1     NICK
2    KRISH
3     JACK
Name: Name, dtype: object

You can try this too if you don't like RegEx:

df['Name'].apply(lambda x: ''.join([letter for letter in x if letter.isupper()]))

For all rows in the Name column, concatenate all letters that are uppercase.

Related