I have 2 data frames. I want to subset df_1 based on df_2 so that the rows in the resulting data frame correspond to the rows in df_2. Here are two example data frames:
df_1 = pd.DataFrame({
"ID": ["Lemon","Banana","Apple","Cherry","Tomato","Blueberry","Avocado","Lime"],
"Color": ["Yellow","Yellow","Red","Red","Red","Blue","Green","Green"]})
df_2 = pd.DataFrame({"Color": ["Red","Blue","Yellow","Green","Red","Yellow"]})
My desired output is df_3, where the "Color" column is the same as in df_2:
df_3 = pd.DataFrame({
"ID": ["Apple","Blueberry","Lemon","Avocado","Cherry","Banana"],
"Color": ["Red","Blue","Yellow","Green","Red","Yellow"]})
When I merge df_1 and df_2, I get duplicated rows because most of the rows in df_2 have multiple matches in df_1.
merged = df_2.merge(df_1, how="left", on="Color")
Dropping duplicates works properly for the "Yellow" color because it has a 2:2 ratio of values in df_2 and options in df_1, but it doesn't work properly for "Red" or "Green" because they have a 2:3 ratio and a 1:2 ratio respectively, resulting in extra rows.
no_duplicates = merged.drop_duplicates(subset = "ID")
Is there a way to subset df_1 where the first occurrence of "Red" in df_2 pulls out the first occurrence of "Red" in df_1, the second occurrence of "Red" in df_2 pulls out the second occurrence of "Red" in df_1, etc.? I would rather not use a loop unless I have no other choice. Thank you.