I have a DataFrame, df, where I would like to replace several values
| user1 | user2 | user3 |
|---|---|---|
| apple | yoo | apple |
| mango | ram | mango |
Instead of doing
df['user1'] = df['user1'].replace(['apple','mango'], [0, 1])
df['user3'] = df['user1'].replace(['apple','mango'], [0, 1])
df['user2'] = df['user2'].replace(['yoo','ram'], [2, 3])
to get the final DataFrame of
| user1 | user2 | user3 |
|---|---|---|
| 0 | 2 | 0 |
| 1 | 3 | 1 |
Is there any way I make the code above more efficient such that I can change the values of apple, mango, yoo and ram with one line of code?
df.replace(['apple', 'mango', 'yoo', 'ram'], [0, 1, 2, 3])works? Unless you actually need different mappings in different columns.