How do I add specific rows to a dataframe based on whether a column value matches a value in a column from another dataframe of a different size?

  dataframe, pandas, python

So, here are my two df’s

We’ll call this df1

Gender    Event       a          b         c Class
0     Men  100m  1200.0  10.971191  139.8393   T11
1     Men  100m  1200.0  10.971191  138.0283   T12
2     Men  100m  1200.0  10.971191  137.0257   T13
3     Men  100m  1200.0   9.188962  176.9927   T33
4     Men  100m  1200.0   9.188962  165.4070   T34
5     Men  100m  1200.0  10.971191  155.0682   T35
6     Men  100m  1200.0  10.971191  150.9139   T36
7     Men  100m  1200.0  10.971191  144.3758   T37
8     Men  100m  1200.0  10.971191  140.0295   T38

And this df2

    Gender Class Event  Time (ms)
24     Men   T11  100m    10950.0
25     Men   T11  100m    11030.0
26     Men   T11  100m    11100.0
27     Men   T11  100m    11140.0
28     Men   T11  100m    11200.0
..     ...   ...   ...        ...
968    Men   T64  100m    13460.0
969    Men   T64  100m    13480.0
970    Men   T64  100m    14180.0
971    Men   T64  100m    14430.0
972    Men   T64  100m    15470.0

What I’d like to do is take the a, b, and c values and add them to columns in the second df, based on whether their adjacent value from "Class" matched that within the second df. As one can see, there are multiple of each unique "Class" value in the second df, but only one in the first.

What I had done in R was create a pointer, however as they don’t exist in Python I am a bit stuck. What I have so far is:

UClass = df2["Class"].unique()
for i in UClass:
   if i in df2["Class"].unique():

I do not want to be hard-coding each value from "Class" in df1, which is why I am trying to get it to loop through looking for the unique values and then add those adjacent a, b, c values to correspond in df2. Any thoughts?

Source: Python Questions

LEAVE A COMMENT