Home > Software engineering >  How to map/replace multiple values in a column for each row in pandas dataframe
How to map/replace multiple values in a column for each row in pandas dataframe

Time:10-23

I have this sample

col1    result
1          A
1,2,3   
2          B
2,3,4   
3,4 
4          D
1,3,4   
3          C

Here's my map variable. vals_to_replace = {'1':'A', '2':'B', '3':'C' , '4':'D'} I map this to col1, and only getting some values from the col result, not sure why why single value got mapped only.

Any ideas on how to solve it?

Thanks

CodePudding user response:

Maybe this is what works for you:

import pandas as pd
df = pd.DataFrame({'col1': ['1', '1,2,3', '2', '2,3,4', '3, 4', '4', '1,3,4', '3']})
translation = {'1':'A', '2':'B', '3':'C' , '4':'D'}
df['result'] = df.col1.str.translate(str.maketrans(translation))
print(df)

Result:

    col1 result
0      1      A
1  1,2,3  A,B,C
2      2      B
3  2,3,4  B,C,D
4   3, 4   C, D
5      4      D
6  1,3,4  A,C,D
7      3      C
  • Related