dataframe pandas子集系列

时间:2015-04-27 14:07:07

标签: python pandas

我有两只pandas Dataframe df1df2。两者都有一个共同的列dealer。我想为df1中出现的所有dealer分组df2。我该怎么做?

1 个答案:

答案 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())]