python - 使用正则表达式对多列求和以选择要求和的列
问题描述
我想执行以下操作:"
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)})
当我们有更多列和更多“正则表达式”匹配时,我想知道是否有更好的方法来做到这一点。
解决方案
使用 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
推荐阅读
- java - Javassist 字节码检测在运行时为 Springboot 配置类创建 NoClassDefFoundError
- python - Kafka - 如何捕获kafka客户端后台线程生成的消息
- javascript - 网站如何检测类似机器人的光标移动
- php - 请问,为什么这个sql更新查询不起作用?
- python - 如果标记 > TotalMarks: TypeError: '>' 在 'list' 和 'int' 的实例之间不支持
- python - 有没有办法检查属性是否有设置器?
- c# - 提取谓词中的冗余
- c# - 如何在信号器路由的 url 中获取参数?
- ruby-on-rails - 提取所有具有特定单词的哈希键
- angular - Angular Material Datepicker:空日期的自定义字段文本