首页 > 解决方案 > 在 Python Pandas 中使用多个通配符

问题描述

感谢您的帮助。非常感激。我已经浏览了 SO 并不能完全得到我希望的答案。

我有我想求和的列的数据框,但想基于通配符排除(所以我希望基于通配符包括但也基于通配符排除)

我的专栏包括:“dose_1”、“dose_2”、“dose_3”...“new_dose”+“infusion_dose_1”+“infusion_dose_2”+更多类似的

我知道如果我想使用通配符求和,我可以

df['new_column'] = df.filter(regex = 'dose').sum(axis = 1)

但是如果我想排除包含 str "infusion" 的列怎么办?

欣赏它!

标签: pythonpandaswildcard

解决方案


regex可能是这项工作的错误工具。基于匹配排除过于复杂,请参阅正则表达式匹配不包含单词的行。只需使用列表推导来选择标签:

df = pd.DataFrame(columns=["dose_1", "dose_2", "dose_3", "new_dose",
                           "infusion_dose_1", "infusion_dose_2", 'foobar'])

cols = [x for x in df.columns if 'dose' in x and 'infusion' not in x]
#['dose_1', 'dose_2', 'dose_3', 'new_dose']

df['new_column'] = df[cols].sum(axis = 1)

推荐阅读