python - 如何根据基于另一个数据框的条件提取熊猫数据框的行
问题描述
我有这两个数据框:
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 行的数据框,其中:
- df1 中的 Points 列的值也在 df2 的 Points 列中
- df2 中列 Sum 的值介于 0 和 2 之间
因此,我想获得这个数据框(无论索引如何):
Points ColX
4 5 5
我尝试了以下但没有奏效:
df1[df1.merge(df2, on = 'Points')['Sum'] <= 2 and ['Sum']>=0]
你能帮我找到正确的代码吗?
解决方案
尝试这个:
df1[df1['Points'].isin(df2.query('0 <= Sum <= 2')['Points'])]
输出:
Points ColX
4 5 5
解释:
df2.query('0 <= Sum <=2')
首先过滤 df2 以仅有效记录- 然后使用
isin
过滤器 df2 Points 列的布尔索引。
推荐阅读
- java - C# AES 加密
- neo4j - 获取按邻近度排序的节点和在同一级别按日期排序的节点
- authentication - Auth0 - 如何创建没有密码的用户,或如何在验证电子邮件中包含密码
- c++ - 使用可变参数模板连接多个 std::array 对象
- iframe - 此身份验证流程安全吗?
- asp.net - IIS 应用程序池每 15 天停止一次,无需任何配置
- java - 嵌套循环中模的时间复杂度
- python - 如何在 python 数据框中创建 nm 映射表?
- git - 如何为远程标签执行 `git log` 或 `git describe`?
- nuxt.js - 如何在 NuxtJS 上获取 Tailwindcss 2.x