我有以下数据框:
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?
最佳答案
最简单的方法是使用带有内部连接的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/