python - 根据Python中的另一个数据框选择数据框的行
问题描述
我有以下数据框:
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})
print(df1)
A B C D
0 foo one 0 0
1 bar one 1 2
2 foo two 2 4
3 bar three 3 6
4 foo two 4 8
5 bar two 5 10
6 foo one 6 12
7 foo three 7 14
我希望按如下方式选择df1
行df2
:
df2 = pd.DataFrame({'A': 'foo bar'.split(),
'B': 'one two'.split()
})
print(df2)
A B
0 foo one
1 bar two
这是我在 Python 中尝试过的方法,但我只是想知道是否还有另一种方法。谢谢。
df = df1.merge(df2, on=['A','B'])
print(df)
这是预期的输出。
A B C D
0 foo one 0 0
1 bar two 5 10
2 foo one 6 12
解决方案
最简单的是merge
与内部连接一起使用。
过滤的另一种解决方案:
arr = [np.array([df1[k] == v for k, v in x.items()]).all(axis=0) for x in df2.to_dict('r')]
df = df1[np.array(arr).any(axis=0)]
print(df)
A B C D
0 foo one 0 0
5 bar two 5 10
6 foo one 6 12
或创建MultiIndex
和过滤Index.isin
:
df = df1[df1.set_index(['A','B']).index.isin(df2.set_index(['A','B']).index)]
print(df)
A B C D
0 foo one 0 0
5 bar two 5 10
6 foo one 6 12
推荐阅读
- javascript - 比较两个嵌套数组和对象以查找差异
- arrays - MongoDB $and 仅当 $and 在文档的同一数组索引中为真时才查询 - 特别是对于双重嵌套数组
- git - Git:克隆具有父层次结构的存储库
- flutter - android studio 中未显示 dart 分析器工具窗口
- javascript - 如何为不同的域设置 cookie?
- docker - 使用 Docker-Compose UP 进行 Elixir 测试
- c++ - 函数中使用的函数指针的参数问题
- python-3.x - 搜索 df2.col2 中的字符串作为 df1.col1 中的子字符串,并将其替换为 df2.col1 中的字符串
- sql - SQL对具有不同日期条件的同一列求和
- typescript - 问题从导出导入 Typescript ES6