我已经尝试了几个小时才能在此处找到答案,但是在我的特定情况下我无法解决任何问题。我能找到的最接近的是: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 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

关于python - 使用具有多个元素的字典过滤数据框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52714316/

10-13 04:53