python-3.x - 根据字典值过滤和迭代 pandas 数据帧
问题描述
我正在尝试遍历 pandas 数据框以创建过滤条件,下面是我的代码,它工作正常:-
categories_lst = [
["BEER/ALE/ALCOHOLIC CIDER"],
["CIGARETTES", "CIGARS", "ELECTRONIC SMOKING DEVICES"],
["COLD CEREAL"],
["YOGURT"],
]
threshold_lst = [1, 0.25, 0.25, 0.25]
i = 0
for lst in categories_lst:
# filtering category
df_report = df_us_brand_report[df_us_brand_report["category"].isin(lst)]
df_report = df_report[abs(df_report["change"]) >= threshold_lst[i]]
print(lst)
print(threshold_lst[i])
i += 1
# some other operations
但是,我想优化它,我尝试使用下面的代码,但它失败了,因为列表不可散列。
category_dict = {
["BEER/ALE/ALCOHOLIC CIDER"]: 1,
["CIGARETTES", "CIGARS", "ELECTRONIC SMOKING DEVICES"]: 0.25,
["COLD CEREAL"]: 0.25,
["YOGURT"]: 0.25,
}
for condition, value in category_dict:
filter_condition = (df_us_brand_report["category"].isin(condition)) & (
abs(df_us_brand_report["change"]) >= value
)
# some other operations
任何帮助,将不胜感激。
解决方案
使用元组:
category_dict = {
("BEER/ALE/ALCOHOLIC CIDER", ): 1,
("CIGARETTES", "CIGARS", "ELECTRONIC SMOKING DEVICES"): 0.25,
("COLD CEREAL", ): 0.25,
("YOGURT", ): 0.25,
}
for condition, value in category_dict.items():
filter_condition = (df_us_brand_report["category"].isin(list(condition))) & (
abs(df_us_brand_report["change"]) >= value)
推荐阅读
- scala - 无法过滤存储在 spark 2.2.0 数据框中的 CSV 列
- python - 同时使用多个硒网络驱动程序的正确方法是什么?
- objective-c - 带有 Gmail 和 OAuth2 的 MailCore2 仅在完全访问范围内发送,即 https://mail.google.com
- ruby-on-rails - 当我想要 Rails 中的全局对象时,如何避免常量?
- python - Django 管理用户创建表单中未显示额外字段
- xml - 如何使用正则表达式验证xml中的元素
- android - Xamarin Android Wear - 导航
- powershell - 为什么带有 -Filter 的 Get-MobileDevice 使用变量没有找到任何东西?
- angular - 如何更改 JSON 返回的数据?
- amazon-web-services - 通过 AWS SSM(运行命令)和 S3 在 ec2 上执行 Jmeter