2

I am currently having difficulty replacing a string in my pandas dataframe. So the string that I want to change is "private" -> "pte" and "limited" -> "ltd".

The table looks like:

Column: Company_Name
 1. XXXX private limited
 2. XX (private) limited
 3. yyy pte. limited

My code is:

df['company_name'].str.replace('.*private.+*','pte')
df['company_name'].str.replace('limited$','ltd)
print(df)

But I still get the exact same dataframe that I used pandas to read. Does anybody know why - I checked that I imported re?

1
  • 2
    str.replace is not inplace, it returns the modified Series/column, you need to assign back: df['company_name'] = df['company_name'].str.replace('.*private.+*','pte'), check the docs Commented Jul 11, 2017 at 10:04

3 Answers 3

2

Look:

import pandas as pd

index = [1,2,3]
columns = ['company_name']
data =  ['XXXX private limited','XX (private) limited','yyy pte. limited']
df = pd.DataFrame(data, index=index, columns=columns)

df['company_name'] = df['company_name'].str.replace('private','pte')
df['company_name'] = df['company_name'].str.replace('limited$','ltd')

Result:

 company_name
1  XXXX pte ltd
2  XX (pte) ltd
3  yyy pte. ltd

Now, you have to search how to remove (). symbols.

Have a great day,

MARCUS

Sign up to request clarification or add additional context in comments.

Comments

1

str.replace is not an inplace operation, you have to assign the value back to df['company_name']

Comments

0

The answer above is right. Another choice is that you can use of propety of inplace.

And the code should be:

df['company_name'].str.replace('.*private.+*', 'pte' , inplace = True)
df['company_name'].str.replace('limited$', 'ltd', inplace = True)

Thus the dataframe df can be updated immediately

1 Comment

Welcome to SO and thanks for contributing! However, I'm pretty sure this does not work: TypeError: replace() takes no keyword arguments. Additionally, you are missing a terminating '

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.