I want two join two dataframes, with different indices, and return a new dataframe containing the indices from the two frames where there is a match.
df_a
contains the resulting value from a number of simulations. df_b
, for each Group and three different "Levels", contains the resulting simulation value we want to retrieve. The final output should be a dataframe with each group, level and the matching simulation. For instance for 'Group_1', 'Level_1' simulation, 'Sim_5', is the simulation we want.
df_a = pd.DataFrame({'Group_1': [5, 2, 3, 4, 1],
'Group_2': [1, 4, 3, 2, 5],
'Group_3': [2, 1, 5, 4, 3]},
index=['Sim_1', 'Sim_2', 'Sim_3', 'Sim_4', 'Sim_5'])
df_b = pd.DataFrame({'Group_1': [1, 2, 4],
'Group_2': [2, 5, 1],
'Group_3': [3, 2, 4]},
index=['Level_1', 'Level_2', 'Level_3'])
# Expected output
df_c = pd.DataFrame(data=['Sim_5', 'Sim_2', 'Sim_4', 'Sim_4', 'Sim_5', 'Sim_1', 'Sim_5', 'Sim_1', 'Sim_4'],
index=pd.MultiIndex.from_product([['Group_1', 'Group_2', 'Group_3'], ['Level_1', 'Level_2', 'Level_3']]))
Out[54]:
0
Group_1 Level_1 Sim_5
Level_2 Sim_2
Level_3 Sim_4
Group_2 Level_1 Sim_4
Level_2 Sim_5
Level_3 Sim_1
Group_3 Level_1 Sim_5
Level_2 Sim_1
Level_3 Sim_4
Can anyone think of a nice way to achieve this? I am probably able to 'brute-force' something, but I would prefer a nice clean implementation.
df_b
where the last index should beLevel_3
.