如何累积/收集/总结列表 - Python

时间:2017-04-16 23:22:37

标签: python list sum collect

我真的很喜欢使用python。我需要实现以下目标。

我有一个清单

[
  ['1604201722','16/04/2017','22', 100.0, 10.0, 110.0],<br>
  ['1604201722','16/04/2017','22', 100.0, 10.0, 110.0],<br>
  ['1604201719','16/04/2017','19', 100.0, 10.0, 110.0]<br>
]

线结构

['     ID   ','    DATE  ','Hour',  CANT, CANT, CANT]
['1604201722','16/04/2017','22'  ,  100.0,10.0, 110.0]

我需要累积这样的值:

['1604201722','16/04/2017', '22' , 200.0, 20.0, 240.0]
['1604201719','16/04/2017', '19' , 100.0, 10.0, 110.0]

请帮忙!
感谢

1 个答案:

答案 0 :(得分:1)

尝试使用pandas dataframe

import pandas as pd
d = [
  ['1604201722','16/04/2017','22', 100.0, 10.0, 110.0],
  ['1604201722','16/04/2017','22', 100.0, 10.0, 110.0],
  ['1604201719','16/04/2017','19', 100.0, 10.0, 110.0]
]
df= pd.DataFrame(d,columns=['ID','DATE','HOUR','col1','col2','col3'])
print(df.groupby(['ID','DATE','HOUR']).sum())

将提供此输出:

ID         DATE       HOUR   col1  col2   col3                   
1604201719 16/04/2017 19    100.0  10.0  110.0
1604201722 16/04/2017 22    200.0  20.0  220.0