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

标签 python pandas dataframe filter

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

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

相关文章:

python - 如何在 Python 中组合列表和字典?

python - 在 Azure Function (Python) 中将图形 API 与系统分配的托管标识结合使用

python - 如何使用 matplotlib 绘制复杂的条形图——具有多行条形的多个子图?

python - 将列表放入数据框中时列传递错误

python - Pandas 通过选择最可能的行将多行折叠成一行

python - 使用源 url 创建具有不同路径和方案的新 url 的 pythonic 方法是什么?

Python:字典数据结构的树状实现

python - 将数字与字符串分开并使用 pandas 添加数字

python - 使用 Pandas 向 csv 文件添加独立标题

Python、Pandas 删除 Excel 中的行