Search code examples
pythonlistsumcollect

How to Accumulate/Collect/Sum list?


I'm really new using Python. I need to achieve the following.

I have a list

[
  ['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>
]

Line structure is

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

I need to accumulate the values like this:

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

Solution

  • Try using a 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())
    

    Which will give this output:

    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