【问题标题】:Filtering a Dataframe using dictionary with multiple elements使用具有多个元素的字典过滤数据框
【发布时间】:2019-03-13 20:03:39
【问题描述】:

我已经尝试了几个小时来在这里找到答案,但在我的特殊情况下我无法找到任何答案。我能找到的最接近的是:Apply multiple string containment filters to pandas dataframe using dictionary

我有一个包含以下列的交易价格的 pd.Dataframe:

df1 = database[['DealID',
         'Price',
         'Attribute A',
         'Attribute B',
         'Attribute C']]

属性分为以下几类:

filter_options = {
    'Attribute A': ["A1","A2","A3","A4"],
    'Attribute B': ["B1","B2","B3","B4"],
    'Attribute C': ["C1","C2","C3"],
}

我想使用 filter_options 的子集过滤 df1,每个键有 多个 值:

filter = {
    'Attribute A': ["A1","A2"],
    'Attribute B': ["B1"],
    'Attribute C': ["C1","C3"],
}

当字典中每个键只有一个值时,以下内容可以正常工作。

df_filtered = df1.loc[(df1[list(filter)] == pd.Series(filter)).all(axis=1)]

但是,我能否通过每个键的多个值获得相同的结果?

谢谢!

【问题讨论】:

标签: python pandas dataframe filter


【解决方案1】:

我相信您需要更改变量 filter 因为 python 保留字,然后使用 list comprehensionisinconcat 作为布尔掩码:

df1 = pd.DataFrame({'Attribute A':["A1","A2"],
                    'Attribute B':["B1","B2"],
                    'Attribute C':["C1","C2"],
                    'Price':[140,250]})

filt = {
    'Attribute A': ["A1","A2"],
    'Attribute B': ["B1"],
    'Attribute C': ["C1","C3"],
}

print (df1[list(filt)])
  Attribute A Attribute B Attribute C
0          A1          B1          C1
1          A2          B2          C2

mask = pd.concat([df1[k].isin(v) for k, v in filt.items()], axis=1).all(axis=1)
print (mask)
0     True
1    False
dtype: bool

df_filtered = df1[mask]
print (df_filtered)
  Attribute A Attribute B Attribute C  Price
0          A1          B1          C1    140

【讨论】:

    猜你喜欢
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    相关资源
    最近更新 更多