'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
Solution 1:[1]
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())])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Biegeleisen |
