1

I have dataframe with many rows. I want to use pd.replace to replace values in entire columns.

import pandas as pd
import re
list = ['MD 15241', 'MD', 'TD', 'TD 15487']
a = pd.DataFrame(list)
b = a.copy()

b.replace(r'[A-Z]{2}', 'USA', inplace = True)
b

output

    0
0   MD 15241
1   MD
2   TD
3   TD 15487

I tried r'MD' or r'TD' , it works.

1
  • You might want to add the tag Pandas Commented Sep 14, 2017 at 4:40

2 Answers 2

2

You need regex=True in the replace method:

b.replace(r'[A-Z]{2}', 'USA', inplace=True, regex=True)

b
#0
#0  USA 15241
#1  USA
#2  USA
#3  USA 15487
Sign up to request clarification or add additional context in comments.

Comments

0
def replace_string_inside_df(df):
    df.replace(r'[^a-zA-Z0-9]', ' ', inplace=True, regex=True)
    return df

print(replace_string_inside_df(df))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.