在Python中使用多个通配符

2024-09-27 04:20:27 发布

您现在位置:Python中文网/ 问答频道 /正文

谢谢你的帮助。非常感谢。我看了一遍S.O.,没能得到我所希望的答案

我有一个数据框,其中包含我希望求和的列,但希望基于通配符排除这些列 (所以我希望包括基于通配符的,但也排除基于通配符的)

我的专栏包括: “剂量1”、“剂量2”、“剂量3”。。。“新剂量”+“输液剂量1”+“输液剂量2”+更多类似情况

我明白如果我想用通配符求和,我可以

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

但如果我想排除包含str“infusion”的列呢

谢谢你


Tags: 数据答案dfnew情况columnfilterregex
1条回答
网友
1楼 · 发布于 2024-09-27 04:20:27

regex此作业可能使用了错误的工具。基于匹配进行排除过于复杂,请参见Regular expression to match a line that doesn't contain a word。只需使用列表来选择标签:

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)

相关问题 更多 >

    热门问题