How to do endswith string replacement in dataframe

Viewed 1362

I have a dataframe df that looks like this:

      Company Name     ID
0        Finl Corp    111
1          Fund Tr    222
2          Invt Fd    333           
3          Govt Fd    444
4      Trinity Inc    555

And I'm replacing strings that are commonly abbreviated:

df['Company Name'] = df['Company Name'].str.replace('Finl', 'Financial')
df['Company Name'] = df['Company Name'].str.replace('Tr', 'Trust')
df['Company Name'] = df['Company Name'].str.replace('Invt', 'Investment')
df['Company Name'] = df['Company Name'].str.replace('Fd', 'Fund')
df['Company Name'] = df['Company Name'].str.replace('Govt', 'Government')

But how do I replace Tr with Trust only when Tr is the last two characters of a string, like row 1 (but not row 4)?

Can I do something like?

df['Company Name'] = df['Company Name'].str.endswith(' Tr').replace(' Tr', ' Trust') so that the output is:

      Company Name    ID  
0   Financial Corp   111
1       Fund Trust   222
2  Investment Fund   333
3  Government Fund   444
4      Trinity Inc   555
4 Answers

you can use $ to match the end of the line in replace:

df['Company Name'] = df['Company Name'].str.replace(' Tr$', ' Trust')

Replace more than one thing at once using replace with regex=True:

repl_dict = {'Govt': 'Government', 'Fd$': 'Fund',}                                                                                                  
df['Company Name'].replace({k : v for k, v in repl_dict.items()}, 
                           regex=True)                                                            

0          Finl Corp
1            Fund Tr
2          Invt Fund
3    Government Fund
4        Trinity Inc
Name: Company Name, dtype: object

Write a def expand_trust(s): helper function, that replaces "Tr" with "Trust".

Then use .apply( ... ) to modify your dataframe:

df["Company Name"] = df["Company Name"].apply(expand_trust)

Your helper can use .endswith( ... ), but you might find that $ in a regex is more convenient.

You don't need str.replace if you first select the rows you want to replace with df.loc and assign them to the corresponding replacement string:

df.loc[df['Company Name'].str.endswith('Finl')] = 'Financial'

I suggest putting the text/replacement duos in a dictionary and perform this in a loop, instead of repeatedly overwriting the whole df['Company Name'] column, e.g:

replace_dict = {'Finl': 'Financial', 
                'Tr': 'Trust', 
                'Invt': 'Investment', 
                'Fd': 'Fund', 
                'Govt': 'Government'}

for k, v in replace_dict.items(): 
    df.loc[df['Company Name'].str.endswith(k)] = v 
Related