首页 > 解决方案 > 根据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

我希望按如下方式选择df1df2

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

使用 pandas 使用数据框中的两个不同列选择行?

根据另一个 DataFrame 选择一个 DataFrame 的列

标签: pythonpandasdataframe

解决方案


最简单的是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

推荐阅读