Andrew
Andrew

Reputation: 137

How to map two data frames in python?

I have a data frame which can has n number of P_Id values for each Id.

X = Id    P_Id     Value
    1      a_1      56
    1      a_2      76
    2      a_1      67
    2      a_2      78
    2      a_3      98

I have another data frame

Y =  Id  Name 
     1    Erwin
     2    Joseph
     3     Nik

I want the out put data frame to be

Output =  Id  a_1  a_2   a_3  Name
          1    56   76   nan   Erwin
          2    67   78   98    Joseph

Upvotes: 1

Views: 368

Answers (1)

ThePyGuy
ThePyGuy

Reputation: 18426

Inner merge x, and y, then pivot this merged dataframe,then merge back to the second dataframe, finally, you can reset the index, .

x.merge(y, how='inner', on='Id').pivot(columns='P_Id', values='Value').merge(y, on='Id').reset_index()

OUTPUT:

   Id   a_1   a_2   a_3    Name
0   1  56.0  76.0   NaN   Erwin
1   2  67.0  78.0  98.0  Joseph

Upvotes: 3

Related Questions