首页 > 解决方案 > 使用正则表达式对多列求和以选择要求和的列

问题描述

我想执行以下操作:"

test = pd.DataFrame({'A1':[1,1,1,1],
              'A2':[1,2,2,1],
              'A3':[1,1,1,1],
              'B1':[1,1,1,1],
              'B2':[pd.NA, 1,1,1]})
result = pd.DataFrame({'A': test.filter(regex='A').sum(axis=1),
 'B': test.filter(regex='B').sum(axis=1)})

当我们有更多列和更多“正则表达式”匹配时,我想知道是否有更好的方法来做到这一点。

标签: pythonpandas

解决方案


使用 dict 理解而不是多个重复代码,例如:

L = ['A','B']
df = pd.DataFrame({x: test.filter(regex=x).sum(axis=1) for x in L})

或者,如果可能,通过仅选择第一个字母使用来简化解决方案:

df = test.groupby(lambda x: x[0], axis=1).sum()
print (df)
   A    B
0  3  1.0
1  4  2.0
2  4  2.0
3  3  2.0

如果正则表达式应该由|和 gt 所有列子字符串连接,则使用:

vals = test.columns.str.extract('(A|B)', expand=False)
print (vals)
Index(['A', 'A', 'A', 'B', 'B'], dtype='object')

df = test.groupby(vals, axis=1).sum()
print (df)
   A    B
0  3  1.0
1  4  2.0
2  4  2.0
3  3  2.0

推荐阅读