Home > Enterprise >  Replace pandas column values with dictionary values
Replace pandas column values with dictionary values

Time:04-05

I have a dictionary like as shown below

OUTPUT = {'supplier': {0: 'ABCD',
  1: 'DEFG',
  2: 'GHIK',
  3: 'JKL'},
 'region': {0: 'KOREA',
  1: 'AUS/NZ',
  2: 'INDIA',
  3: 'ASEAN',
  4: 'HK / CHINA'}}

ID,supplier,region,subject
1, 0, 3, TEST
2, 1, 2, EXAM
3, 3, 4, VIVA

df = pd.read_clipboard(sep=',')

I would like to replace the values in column supplier and region with their corresponding mapping value from the dictionary

I tried the below

df["supplier"].replace(output) # not works
df['supplier'].map(output) # not works

But this threw an error as shown below

AttributeError: 'Series' object has no attribute '_replace_columnwise'

I expect my output to be like as shown below

ID,supplier,region,subject
1, ABCD, ASEAN, TEST
2, DEFG, INDIA, EXAM
3, JKL, HK/CHINA, VIVA

CodePudding user response:

You could use map in loop:

for k,v in OUTPUT.items():
    df[k] = df[k].map(v)

or simply use replace as suggested by @piRSquared:

df = df.replace(OUTPUT)

Output:

   ID supplier      region subject
0   1     ABCD       ASEAN    TEST
1   2     DEFG       INDIA    EXAM
2   3      JKL  HK / CHINA    VIVA
  • Related