python - 添加了示例数据:在数据框中分别聚合几个类似命名的列
问题描述
我有一个大的df。在这些列中,如果 fooX_bar 出现在特定观察中,则虚拟 fooX_bar 为 1,而体积测量值 fooX_bar_volume。
我想在新的数据框“aggregate_ranks”中选择和聚合这些列。出于某种原因,我的 dfs 字典中的每个 df 都有一个“空行”,所有值都为 0。我既不明白为什么会发生这种情况,也不明白如何预防。
我有一个解决方法,但想了解这里发生了什么。
我的代码:
#example data
import pandas as pd
data = {'foo1_bar': [1, 0, 1, 1, 1, 0, 1],
'foo2_bar': [1, 1, 1, 0, 1, 0, 1],
'foo3_bar': [1, 1, 1, 1, 1, 1, 0],
'foo1_bar_volume': [56.3, 0, 77.1, 69, 52, 0, 14],
'foo2_bar_volume': [23, 13, 18.5, 0, 9, 0, 25.4],
'foo3_bar_volume': [89, 67, 75.15, 64.45, 44, 67.9, 0]
}
df = pd.DataFrame(data)
aggregate_ranks=pd.DataFrame()
bar_cols = [col for col in df.columns if col.endswith('_bar')]
d = {}
for c in bar_cols:
d[c] = pd.DataFrame()
agg_by = {
'count': (c,'sum'),
'volume':(c+'_volume','sum')
}
#d[c] = d[c][(d[c].T != 0).any()] #workaround to delete the superfluous columns
d[c] = df.groupby([pd.Grouper(key=c)]).agg(**agg_by)
d[c]['name'] = d[c].index.name #adding the name of the aggregated column
d[c] = d[c].reset_index(drop=True)
aggregate_ranks = aggregate_ranks.append(d[c])
print(aggregate_ranks)
count volume name
0 0 0.0 foo1_bar
1 5 268.4 foo1_bar
0 0 0.0 foo2_bar
1 5 88.9 foo2_bar
0 0 0.0 foo3_bar
1 6 407.5 foo3_bar
编辑:添加示例数据、我的“解决方法”和一些注释
解决方案
推荐阅读
- java - 您如何将这个问题分解为子问题并使用动态规划?
- reactjs - 如何使用 Hook(ForwardRef 概念)在子组件中调用父方法
- reactjs - 使用 React 和 .Net Core Web Api 作为附件发送 PDF
- javascript - SyntaxError: ..\node_modules\react-router-native\BackButton.js:目前未启用对实验性语法“classProperties”的支持 (7:14):
- python - 如何对接收到的输出数组进行排序?
- android - 此应用是为较旧的 android 版本构建的,可能无法正常运行
- c - 如何在 C 函数中返回错误符号?
- api - 如何从 DBpedia 获取具有高度的所有人员实例?
- azure - 是否可以在一个租户中注册 Azure 应用程序,而在另一个租户中注册应用程序服务
- regex - 正则表达式捕获该字符串包含字母数字、下划线和空格,但以字母开头