2

Below is sample Dataframe

data = {'A': ['hi UK','hi IN','hi US']}

df = pd.DataFrame(data)

I wanted to update UK, IN values for A column from matching dict below

abs = {'U': 'UK -- extra', 'UK': 'test Kingdom', 'IN':'India'}

then I used replace function (pandas.DataFrame.replace)

df['A'] = df['A'].replace(to_replace = abs, regex=True)
print(df)

                           A
0  hi test Kingdom -- extraK
1                   hi India
2  hi test Kingdom -- extraS

Its replacing U first by UK -- extra and again UK with test kingdom so final result is hi test Kingdom -- extraK idially it should give test kingdom

The expected output is

                 A
0  hi test Kingdom
1         hi India
2            hi US

Am i missing any thing or is there anyway to achieve above result.

Thanks in advance.

1 Answer 1

2

I think word boundary should help here for match UK, US and no U:

data = {'A': ['hi UK','hi IN','hi US']}

d = {'U': 'UK -- extra', 'UK': 'test Kingdom', 'IN':'India'}

d = {r'\b{}\b'.format(k):v for k, v in d.items()}
df = pd.DataFrame(data)

df['A'] = df['A'].replace(to_replace = d, regex=True)
print(df)
                 A
0  hi test Kingdom
1         hi India
2            hi US
Sign up to request clarification or add additional context in comments.

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.