我一直在研究堆栈溢出问题来解决这个问题,但我还没有找到解决方案。
我有一个如下所示的数据框df
:
value
pod 22 72 79 86 87 88
time_stamp
2016-10-03 10.160000 0.000000 0.000000 32.004001 5.334000 11.176000
2016-10-10 0.000000 0.000000 0.000000 2.032000 0.000000 0.000000
2016-10-17 16.002001 0.000000 8.636000 21.336001 1.778000 6.604000
2016-10-24 2.032000 6.604000 71.628004 19.050001 0.508000 2.540000
2016-10-31 3.556000 21.590000 0.000000 0.000000 2.032000 2.794000
2016-11-07 3.302000 10.160000 0.762000 0.254000 1.270000 2.540000
2016-11-14 27.686001 44.704001 22.606001 1.524000 26.670001 42.164001
2016-11-21 68.072001 56.896002 14.732000 8.128000 23.114001 63.500002
我df.head(5).to_dict()
时的输出如下所示:
{('value', 22): {Timestamp('2016-10-03 00:00:00'): 10.159999966599999,
Timestamp('2016-10-10 00:00:00'): 0.0,
Timestamp('2016-10-17 00:00:00'): 16.0020005107,
Timestamp('2016-10-24 00:00:00'): 2.0320000648500001,
Timestamp('2016-10-31 00:00:00'): 3.5560001134900006},
('value', 72): {Timestamp('2016-10-03 00:00:00'): 0.0,
Timestamp('2016-10-10 00:00:00'): 0.0,
Timestamp('2016-10-17 00:00:00'): 0.0,
Timestamp('2016-10-24 00:00:00'): 6.6040000915499997,
Timestamp('2016-10-31 00:00:00'): 21.589999973800001},
('value', 79): {Timestamp('2016-10-03 00:00:00'): 0.0,
Timestamp('2016-10-10 00:00:00'): 0.0,
Timestamp('2016-10-17 00:00:00'): 8.6360000968000001,
Timestamp('2016-10-24 00:00:00'): 71.628004074100005,
Timestamp('2016-10-31 00:00:00'): 0.0},
我想要对列进行分组并对所有值求和。我被卡住了,因为这似乎是一个多级索引。
当我执行此操作s = df.sum(axis=1, level=[1]); s
时,它会删除第一行:value
。如何将列相加?
输出可能只是一个简单的数据框,它将value
列相加,因此它看起来像:
pod 22 72 79...
2016 100 120 110...
2017 80 90 72...
答案 0 :(得分:2)
沿着0 th 轴似乎需要sum
:
df
value
22 72 79
2016-10-03 10.160000 0.000 0.000000
2016-10-10 0.000000 0.000 0.000000
2016-10-17 16.002001 0.000 8.636000
2016-10-24 2.032000 6.604 71.628004
2016-10-31 3.556000 21.590 0.000000
df.sum(axis=0).to_frame().T
value
22 72 79
0 31.750001 28.194 80.264004
如果您想按年度进行分组操作,请在groupby
上致电index.year
:
df.groupby(df.index.year).sum()
value
22 72 79
2016 31.750001 28.194 80.264004