Skip to content Skip to sidebar Skip to footer

How To Use Map Function For Multiindex Dataframe Using Pandas?

I have a data frame like as shown below df = pd.DataFrame({'source_code':['11','11','12','13','14',np.nan], 'source_description':['test1', 'test1','test2','test3

Solution 1:

This seems to be a fairly standard merge with some renaming:

(df.merge(hash_file, left_on = ['source_code','source_description'], right_on = ['source_id','source_code'])
    .drop(columns = ['key_id','source_id','source_code_y'])
    .rename(columns = {'source_code_x':'source_code','hash_id':'key_id'})
)

output

    source_code source_description  key_id
0   11          test1               911
1   11          test1               911
2   12          test2               512
3   13          test3               713

Using map (for updated input values in the question)

df['key_id'] = df.set_index(['source_code','source_description']).index.map(id_file)

output

    source_code source_description  key_id
011          test1               911.0111          test1               911.0212          test2               512.0313          test3               713.0414NaNNaN5NaN         test5               NaN

Post a Comment for "How To Use Map Function For Multiindex Dataframe Using Pandas?"