根据 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

我希望通过 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

使用熊猫从数据框中使用两个不同的列来选择行?

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

原文由 ah bon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 403
2 个回答

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

原文由 jezrael 发布,翻译遵循 CC BY-SA 4.0 许可协议

# The .merge method performs an inner join by default.
# The resulting dataframe will only have rows where the
# merge column value exists in both dataframes

x = df_only_english.merge(train_orders.assign(id=train_orders.id))
x

Unnamed: 0  language    score   id  iso_language_name   is_en   cell_order
0   0   en  0.999998    00015c83e2717b  English English 2e94bd7a 3e99dee9 b5e286ea da4f7550 c417225b 51e3cd89 2600b4eb 75b65993 cf195f8b 25699d02 72b3201a f2c750d3 de148b56...
1   1   en  0.999999    0001bdd4021779  English English 3fdc37be 073782ca 8ea7263c 80543cd8 38310c80 073e27e5 015d52a4 ad7679ef 7fde4f04 07c52510 0a1a7a39 0bcd3fef 58bf360b
2   2   en  0.999996    0001daf4c2c76d  English English 97266564 a898e555 86605076 76cc2642 ef279279 df6c939f 2476da96 00f87d0a ae93e8e6 58aadb1d d20b0094 986fd4f1 b4ff1015...

原文由 Oscar Rangel 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题