Skip to main content
 首页 » 编程设计

python之使用具有多个元素的字典过滤 Dataframe

2024年12月31日10zhengyun_ustc

我已经尝试了几个小时来在这里找到答案,但我无法在我的特定情况下找到任何答案。我能找到的最接近的是: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)] 

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

谢谢!

请您参考如下方法:

我相信您需要更改变量 filter 因为 python 保留字然后使用 list comprehension 和 isin和 concat对于 bool 掩码:

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