【问题标题】:How to select rows based on two column that must contain specific value? [duplicate]如何根据必须包含特定值的两列选择行? [复制]
【发布时间】:2020-04-05 01:06:18
【问题描述】:

我有一个数据集,在某个字段上有很多不正确的重复项,在我的可重现示例中,有不同颜色和形状的连续重复项。我的实际数据框具有正确的颜色和形状以进行串行映射,并且需要选择正确的行。

例子:

import pandas as pd

items = pd.DataFrame({
    'serial': ['0001', '0001', '0001', '0002', '0002', '0002'],
    'color': ['Blue', 'Red', 'Green', 'Blue', 'Red', 'Green'],
    'shape': ['Square', 'Circle', 'Star', 'Square', 'Circle', 'Star'],
    'more_data': ['G', 'H', 'I', 'J', 'K', 'L'],
    'even_more_data': ['A', 'B', 'C', 'D', 'E', 'F']
})

real = pd.DataFrame({
    'serial': ['0001', '0002'],
    'color': ['Blue', 'Red'],
    'shape': ['Square', 'Circle']
})

那么,

Out[1]: items
    serial  color   shape   more_data   even_more_data
0   0001    Blue    Square  G           A
1   0001    Red     Circle  H           B
2   0001    Green   Star    I           C
3   0002    Blue    Square  J           D
4   0002    Red     Circle  K           E
5   0002    Green   Star    L           F

Out[2]: real
    serial  color   shape
0   0001    Blue    Square
1   0002    Red     Circle

我需要使用 'real' 来选择 'items' 中的正确行,所以预期的结果是:

Out[3]: 
    serial  color   shape   more_data   even_more_data
0   0001    Blue    Square  G           A
4   0002    Red     Circle  K           E

【问题讨论】:

    标签: python pandas dictionary pandas-loc


    【解决方案1】:

    你可以使用合并:

    real.merge(items)                                                                                                                                                                    
    

    输出

    Out[305]: 
      serial color   shape more_data even_more_data
    0   0001  Blue  Square         G              A
    1   0002   Red  Circle         K              E
    

    【讨论】:

    • 这比我想象的要简单。我想我正在搜索错误的关键字以找到正确的答案。谢谢。
    • @geistmate 很高兴我能帮上忙!如果你喜欢这个答案,看看这个:meta.stackexchange.com/questions/5234/…
    猜你喜欢
    • 1970-01-01
    • 2014-08-04
    • 2021-09-15
    • 2019-05-20
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多