Demi
Demi

Reputation: 234

How to replace values in a column if column is a list of values?

I have a dataset that looks like this:

ID Language
1 2945
2 2945, 2344
3 NaN
4 2945, 5657,2344

I want it to look like this:

ID Language
1 English
2 English, Arabic
3 NaN
4 English, French, Arabic

How can I replace values if I know that:

({2945:'English',2344:'Arabic',5657:'French'})

I tried this one:

df['Language'].str.replace({2945:'English',2344:'Arabic',5657:'French'})

But it didn't work

Upvotes: 1

Views: 73

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522181

We can try using str.replace with a lambda function:

d = {2945:'English', 2344:'Arabic', 5657:'French'}
df["Language"] = df["Language"].str.replace(r'\d+', lambda m: d[int(m.group())])

Upvotes: 2

Related Questions