如何使用 pandas 从一个数据帧中查找另一个数据帧中的值?

Pol*_*lly 5 python indexing merge conditional-statements pandas

I have two dataframes:

    df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],'B': ['B7', 'B4', 'B0', 'B3'] })
    df2 = pd.DataFrame({'A': ['A4', 'A3', 'A7', 'A8'],'B': ['B0', 'B1', 'B2', 'B3']})
Run Code Online (Sandbox Code Playgroud)

我需要从列中获取所有公共值B,所以这里是 B0B3

使用df1.B.isin(df2.B)给了我False False True True,但不是值列表。

jez*_*ael 7

你需要boolean indexing

print (df1[df1.B.isin(df2.B)])

    A   B
2  A2  B0
3  A3  B3

print (df1.ix[df1.B.isin(df2.B), 'B'])
2    B0
3    B3
Name: B, dtype: object

print (df1.ix[df1.B.isin(df2.B), 'B'].tolist())
['B0', 'B3']
Run Code Online (Sandbox Code Playgroud)

另一个解决方案merge

print (pd.merge(df1,df2, on='B'))
  A_x   B A_y
0  A2  B0  A4
1  A3  B3  A8

print (pd.merge(df1,df2, on='B')['B'])
0    B0
1    B3
Name: B, dtype: object
Run Code Online (Sandbox Code Playgroud)