python - 根据 Python 中的另一个数据框选择数据框的行

标签 python pandas dataframe

我有以下数据框:

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

我希望通过df2选择df1中的行,如下:

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

Using pandas to select rows using two different columns from dataframe?

Select Columns of a DataFrame based on another DataFrame

最佳答案

最简单的方法是使用带有内部连接的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

关于python - 根据 Python 中的另一个数据框选择数据框的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54006298/

相关文章:

python - 使用 DataFrame 合并(连接)4 个具有不同 ID 和多个值的不同 CSV 文件

python - 将列从一个数据框映射到另一个数据框以创建新列

python - 用数据框的行值替换子列表中的第二项

python - 忽略 NaN 的 Pandas 分组和转换

python - 图像像素上的 matplotlib 标记/掩码

python - Writelines 写入没有换行符的行,只是填充文件

python - 有效地获得 3 个不同大小和类型的 numpy 数组的排列

python - 在 Pandas DataFrame 中选择包含至少一个 True 值的列的最佳解决方案

python - 使用 urllib2 超时重试加载页面?

python - (有)python socketserver 相对于常规套接字对象的性能优势吗?