Home > Enterprise >  Combining pandas dataframes according to other dataframes
Combining pandas dataframes according to other dataframes

Time:02-13

Right now, I have 3 pandas dfs that I want to combine. Below is a short version of what I'm working with. Basically, dfs 2 and 3 have the indices that correspond to df1. I want to create another column on the first df that has the labels I want according to the indices of dfs 2 and 3 (please see below for a reference of what my desired result is). Any help is very appreciated! Thank you!

#df 1 
Animal Number 
2   
4   
6   
9   
11

#df 2
Lions 
2   
11

#df 3
Tigers 
4   
6   
9   

This is what I would want my result to look like:

Animal #  Animal Type
0   2   Lion
1   4   Tiger
2   6   Tiger
3   9   Tiger
4   11  Lion

CodePudding user response:

Try:

m = pd.concat([df2, df3], axis=1).stack().reset_index().set_index(0)['level_1']
df1['Animal Type'] = df1['Animal Number'].map(m)
print(df1)

Output:

   Animal Number Animal Type
0              2       Lions
1              4      Tigers
2              6      Tigers
3              9      Tigers
4             11       Lions
  • Related