How to combine consecutive data in a dataframe and add up value

后端 未结 1 1749
北海茫月
北海茫月 2021-01-26 16:27

I have a dataframe :

 Type:  Volume: Date:
 Q     10      2016.6.1
 Q     20      2016.6.1 
 T     10      2016.6.2 
 Q     10      2016.6.3
 T     20      2016.6         


        
相关标签:
1条回答
  • 2021-01-26 16:53
    import numpy as np
    import pandas as pd
    
    df = pd.DataFrame({"Type":   ["Q", "Q", "T", "Q", "T", "T", "Q"],
                       "Volume": [10,   20,  10,  10,  20,  20,  10],
                       "Date":   ["2016-06-01", "2016-06-01", "2016-06-02", "2016-06-03",
                                  "2016-06-04", "2016-06-05", "2016-06-06"]})
    df["Date"] = pd.to_datetime(df["Date"])
    
    res = df.groupby(by = [df.Type.ne('T').cumsum(), 'Type'], as_index=False).agg({'Volume': 'sum', 'Date': 'first'})
    print(res)
    

    Output:

      Type       Date  Volume
    0    Q 2016-06-01      10
    1    Q 2016-06-01      20
    2    T 2016-06-02      10
    3    Q 2016-06-03      10
    4    T 2016-06-04      40
    5    Q 2016-06-06      10
    
    0 讨论(0)
提交回复
热议问题