Python 使用正则表达式对多个列求和,以选择要求和的列
我想执行以下操作:Python 使用正则表达式对多个列求和,以选择要求和的列,python,pandas,Python,Pandas,我想执行以下操作: 当我们有更多的列和更多的“regex”匹配项时,我想知道是否有更好的方法来做到这一点。使用dict comprehension代替多个重复代码,如: 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() prin
当我们有更多的列和更多的“regex”匹配项时,我想知道是否有更好的方法来做到这一点。使用dict comprehension代替多个重复代码,如:
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
是否可以通过不仅选择第一个字母,而且选择一个通用的正则表达式来概括答案?@Snowflake-我认为不可能,需要首先solution@Snowflake-增加了一个想法,但不是一般性的。
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