我有两只pandas Dataframe df1
和df2
。两者都有一个共同的列dealer
。我想为df1
中出现的所有dealer
分组df2
。我该怎么做?
答案 0 :(得分:0)
使用isin
:
df1[df1['delear'].isin(df2['delear'])]
示例:
In [24]:
df1 = pd.DataFrame({'delear':np.arange(5)})
df2 = pd.DataFrame({'delear':[2,4]})
df1[df1['delear'].isin(df2['delear'])]
Out[24]:
delear
2 2
4 4
在df2' delear'中您可能有重复值的情况您可以通过调用unique
:
In [26]:
df2 = pd.DataFrame({'delear':[2,4,4,4,4]})
df2['delear'].unique()
Out[26]:
array([2, 4], dtype=int64)
然后代码变成:
df1[df1['delear'].isin(df2['delear'].unique())]