Python list group and sum with more fields

后端 未结 4 518
情深已故
情深已故 2021-01-26 05:08

I have a list with two integer fields which I would like to sum (string,integer, integer)

myList= [[[\"26-07-2017\",2,0], [\"26-07-2017\",3,0], [\"27-07-2017\",         


        
4条回答
  •  悲&欢浪女
    2021-01-26 05:46

    You can probably do this with Pandas

    import pandas as pd
    
    df = pd.DataFrame(myList[0])
    answer = df.groupby([0]).sum()
    

    gives me

                1  2
    0               
    26-07-2017  5  0
    27-07-2017  1  1
    

    EDIT: I used your list as is above, but with a few modifications, the code makes a bit more sense:

    # name the columns
    df = pd.DataFrame(myList[0], columns=['date', 'int1', 'int2'])
    
    # group on the date column
    df.groupby(['date']).sum()
    

    returns

                int1  int2
    date                  
    26-07-2017     5     0
    27-07-2017     1     1
    

    and the dataframe looks like:

             date  int1  int2
    0  26-07-2017     2     0
    1  26-07-2017     3     0
    2  27-07-2017     1     0
    3  27-07-2017     0     1
    

提交回复
热议问题