Python 使用具有多个元素的字典筛选数据帧
我已经试了几个小时,想在这里找到一个答案,但在我的特殊情况下,我无法找到任何可行的答案。我能找到的最接近的是: 我有一个交易价格的pd.Dataframe,包含以下列:Python 使用具有多个元素的字典筛选数据帧,python,pandas,dataframe,filter,Python,Pandas,Dataframe,Filter,我已经试了几个小时,想在这里找到一个答案,但在我的特殊情况下,我无法找到任何可行的答案。我能找到的最接近的是: 我有一个交易价格的pd.Dataframe,包含以下列: df1 = database[['DealID', 'Price', 'Attribute A', 'Attribute B', 'Attribute C']] 这些属性分为以下几类: filter_options = { 'Attribute A
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\u选项的子集来过滤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保留字,然后使用列表理解
和布尔掩码:
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
你能添加样本数据吗?你看过这个问题/答案了吗?