我有一个看起来像这样的DataFrame:
FirstDF=
C
A B
'a' 'blue' 43
'green' 59
'b' 'red 56
'c' 'green' 80
'orange' 72
其中A和B设置为索引。我也有一个DataFrame看起来像:
SecondDF=
A B
0 'a' 'green'
1 'b' 'red'
2 'c' 'green'
有没有一种方法可以直接查询第一个DataFrame和最后一个,并获得如下所示的输出?
C
59
56
80
我通过遍历第二个DataFrame来做到这一点,如下所示,但是我想使用pandas逻辑而不是for循环来实现。
data=[]
for i in range(SecondDF.shape[0]):
data.append(FirstDF.loc[tuple(SecondDF.iloc[i])])
data=pd.Series(data)
merge
与参数left_index
and一起使用right_on
:
df = FirstDF.merge(SecondDF, left_index=True, right_on=['A','B'])['C'].to_frame()
print (df)
C
0 59
1 56
2 80
与另一种解决方案isin
的MultiIndex
ES和通过过滤boolean indexing
:
mask = FirstDF.index.isin(SecondDF.set_index(['A','B']).index)
#alternative solution
#mask = FirstDF.index.isin(list(map(tuple,SecondDF[['A','B']].values.tolist())))
df = FirstDF.loc[mask, ['C']].reset_index(drop=True)
print (df)
C
0 59
1 56
2 80
详细说明:
print (FirstDF.loc[mask, ['C']])
C
A B
'a' 'green' 59
'b' 'red' 56
'c' 'green' 80
编辑:
您可以使用merge
外部联接和indicator=True
参数,然后按boolean indexing
以下条件过滤:
df1=FirstDF.merge(SecondDF, left_index=True, right_on=['A','B'], indicator=True, how='outer')
print (df1)
C A B _merge
2 43 'a' 'blue' left_only
0 59 'a' 'green' both
1 56 'b' 'red' both
2 80 'c' 'green' both
2 72 'c' 'orange' left_only
mask = df1['_merge'] != 'both'
df1 = df1.loc[mask, ['C']].reset_index(drop=True)
print (df1)
C
0 43
1 72
对于第二个解决方案,可以通过~
以下方式反转布尔值掩码:
mask = FirstDF.index.isin(SecondDF.set_index(['A','B']).index)
#alternative solution
#mask = FirstDF.index.isin(list(map(tuple,SecondDF[['A','B']].values.tolist())))
df = FirstDF.loc[~mask, ['C']].reset_index(drop=True)
print (df)
C
0 43
1 72
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句