首页 > 解决方案 > 如何根据基于另一个数据框的条件提取熊猫数据框的行

问题描述

我有这两个数据框:

df1 = pd.DataFrame({'Points':[1,2,3,4,5], 'ColX':[9,8,7,6,5]})
df1
    Points  ColX
0        1     9
1        2     8
2        3     7
3        4     6
4        5     5

df2 = pd.DataFrame({'Points':[2,5], 'Sum':[-1,1], 'ColY':[2,4]}) # ColY does not matter, I just added it to say that this dataframe can have other columns that the useful columns for this topic
df2
    Points  Sum  ColY
0        2   -1     2
1        5    1     4

我想获得一个带有 df1 行的数据框,其中:

因此,我想获得这个数据框(无论索引如何):

    Points  ColX
4        5     5

我尝试了以下但没有奏效:

df1[df1.merge(df2, on = 'Points')['Sum'] <= 2 and ['Sum']>=0] 

你能帮我找到正确的代码吗?

标签: pythonpandasdataframe

解决方案


尝试这个:

df1[df1['Points'].isin(df2.query('0 <= Sum <= 2')['Points'])]

输出:

  Points  ColX
4       5     5

解释:

  • df2.query('0 <= Sum <=2')首先过滤 df2 以仅有效记录
  • 然后使用isin过滤器 df2 Points 列的布尔索引。

推荐阅读