【发布时间】:2020-04-30 08:41:32
【问题描述】:
我对 pandas 还很陌生,我正在努力在多索引系列中获得适当的平均值。多指标系列目前是这样的;
idx = pd.MultiIndex.from_tuples([('foo', 111), ('foo', 222),
('bar', 111), ('bar', 222), ('bar', 333),
('baz', 111),
('qux', 111), ('qux', 222)],
names=['ID', 'Account Number'])
df = pd.DataFrame(index=idx, data={'Service 1': 18, 'Service 2': 22, 'Total cost': 40})
df = pd.concat([df], keys=['Cost'], axis=1)
Cost
Service 1 Service 2 Total cost
ID Account Number
foo 111 18 22 40
222 18 22 40
bar 111 18 22 40
222 18 22 40
333 18 22 40
baz 111 18 22 40
qux 111 18 22 40
222 18 22 40
从中提取所有数据的表在帐号级别将成本应用于服务 1 和 2,但它真正需要做的是在 ID 级别应用成本并将成本拆分到帐号之间,所以它是什么应该是这样的;
Cost
Service 1 Service 2 Total cost
ID Account Number
foo 111 9.0 11.000000 20.000000
222 9.0 11.000000 20.000000
bar 111 6.0 7.333333 13.333333
222 6.0 7.333333 13.333333
333 6.0 7.333333 13.333333
baz 111 18.0 22.000000 40.000000
qux 111 9.0 11.000000 20.000000
222 9.0 11.000000 20.000000
我试过df.groupby(['ID']).transform('mean'),但这显然给了我原始数据,我不知道如何到达我需要的地方。
感觉好像我已经在这方面遇到了麻烦,所以任何帮助都将不胜感激。
【问题讨论】:
-
你能做到吗,df.to_dict()?
-
这有点令人困惑,因为我们看不到原始数据框,只有错误和预期的答案。
-
看起来你有多索引列 和 索引。因此,理想情况下,您应该发布一些代码让我们按原样复制您的数据框 - 在这种情况下,打印出来的数据框不会删除它
标签: python pandas group-by pandas-groupby multi-index