首页 > 解决方案 > 添加了示例数据:在数据框中分别聚合几个类似命名的列

问题描述

我有一个大的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

编辑:添加示例数据、我的“解决方法”和一些注释

标签: pythonpandaspandas-groupbyaggregation

解决方案


推荐阅读