我已经尝试了几个小时在这里找到答案,但我无法在我的特定情况下找到任何答案。我能找到的最接近的是:使用字典将多个字符串包含过滤器应用于熊猫数据帧
我有一个PD。包含以下列的交易价格数据帧:
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
:
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