Skip to content Skip to sidebar Skip to footer

How To Efficiently Replace Items Between Dataframes In Pandas?

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 la

Solution 1:

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

Solution 2:

simple use merge

df['Label'] = df.merge(label_df,on='Label')['Description']
    Ages    Label020  Young
122  Young
257  Old

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

Post a Comment for "How To Efficiently Replace Items Between Dataframes In Pandas?"