0

I have 2 df

df = pd.DataFrame({'Ages':[20, 22, 57], 'Label':[1,1,2]})
label_df = pd.DataFrame({'Label':[1,2,3], 'Description':['Young','Old','Very Old']})

I want to replace the label values in df to the description in label_df

Wanted result:

df = pd.DataFrame({'Ages':[20, 22, 57], 'Label':['Young','Young','Old']})
Moshe
  • 461
  • 1
  • 5
  • 15

2 Answers2

2

Use Series.map with Series by label_df:

df['Label'] = df['Label'].map(label_df.set_index('Label')['Description'])
print (df)
   Ages  Label
0    20  Young
1    22  Young
2    57    Old
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

simple use merge

df['Label'] = df.merge(label_df,on='Label')['Description']
    Ages    Label
0   20  Young
1   22  Young
2   57  Old

https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#database-style-dataframe-or-named-series-joining-merging

nay
  • 1,725
  • 1
  • 11
  • 11
  • That's great, but I guess that it would not work in a situation where column name is not equal, for example 'Label' and 'Age_Label', right ? – Moshe Jun 15 '21 at 12:56
  • if column name not the same.you can use left_on and right_on – nay Jun 15 '21 at 14:24