Python: Return 当两个数据框在两个不同的列中共享一个公共值时整行

Python: Return entire row when two data frames share a common value in two different columns

当两个不同的数据帧在两个不同的列中共享一个公共值时,我想打印整行。我可以识别它们,但不是 return 整行,我只能弄清楚如何 return 布尔值,如下所示:

df1 = pd.DataFrame(np.array([[1, 2, 1], 
                             [4, 55, 6], 
                             [1, 8, 88]]),
                   columns=['col1', 'col2', 'col3'])
df1

>>
col1    col2    col3
0   1   2        1
1   4   55       6
2   1   8        88


df2 = pd.DataFrame(np.array([[333, 1, 2], 
                             [55, 8, 88], 
                             [8, 5, 6]]),
                   columns=['col1', 'col2', 'col3'])
df2

>>
    col1    col2    col3
0   333        1    2
1   55         8    88
2   8          5    6


# Return row where df1["col2"] and df2["col1"] have the same values
# the output should print the rows of index 1 and 2

df1['col2'].isin(df2['col1'])

>>
0    False
1     True
2     True
Name: col2, dtype: bool

您可以使用布尔索引:

mask = df1["col2"].isin(df2["col1"])
print(df1[mask])

打印:

   col1  col2  col3
1     4    55     6
2     1     8    88