简体   繁体   中英

Select rows from a data frame where two elements match on a single row from another data frame

Im trying to make a new data frame that has all rows from data frame A where both the values for column x and column y match on one row from data frame B.

I tried finding the index of the rows from data frame B where only the value for column x matched to try and see if i could then match the values for y on those indices but i was not able to retrieve the indices. Also tried iterrows to match the two conditions but that was also unsuccessful.

A={'x':[1,2,3,4],'y':[5,6,7,8]}
B={'x':[1,2,3,10],'y':[5,6,90,8]}

i want code to return

{'x':[1,2],'y':[5,6]}

Suppose you have 2 dataframes:

A=pd.DataFrame({'x':[1,2,3,4],'y':[5,6,7,8]})
B=pd.DataFrame({'x':[1,2,3,10],'y':[5,6,90,8]})

Then you can do:

idx = A.x == B.x
idy = A.y == B.y
ID = idx&idy
A[ID]
    x   y
0   1   5
1   2   6

Or, you may convert it to the desired output:

A[ID].to_dict("list")
{'x': [1, 2], 'y': [5, 6]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM