【问题标题】:how to reset a cumulative sum based on date如何根据日期重置累积总和
【发布时间】:2020-10-14 09:37:00
【问题描述】:

我有一个看起来像 df 的数据框:

date   way 
date_1 A
date_1 B
date_1 A 
date_2 A 
date_2 A 
date_2 A

我想根据这些条件添加一个journey 列:这是一个累积和,当waydate 从一行到下一行不同时递增,并在@987654326 时重置累积和@正在改变

我已经有了:

(df['journey']=df['date'].ne(df['date'].shift())) |(df['way'].ne(df['way'].shift()))).cumsum()

dateway 发生变化时得到累积和。 date 发生变化时如何添加重置?

预期结果是:

date   way journey
date_1 A    1
date_1 B    2
date_1 A    3
date_2 A    1
date_2 A    1
date_2 A    1

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    用途:

    df['journey']= df['way'].ne(df['way'].shift().bfill()).groupby(df['date']).cumsum().add(1)
    print (df)
         date way  journey
    0  date_1   A        1
    1  date_1   B        2
    2  date_1   A        3
    3  date_2   A        1
    4  date_2   A        1
    5  date_2   A        1
    

    或者:

    df['journey'] = (df[['date', 'way']].ne(df[['date', 'way']].shift())
                       .any(axis=1).groupby(df['date']).cumsum())
    
    print (df)
         date way  journey
    0  date_1   A        1
    1  date_1   B        2
    2  date_1   A        3
    3  date_2   A        1
    4  date_2   A        1
    5  date_2   A        1
    

    您的解决方案:

    df['journey'] = ((df['date'].ne(df['date'].shift()) |(df['way'].ne(df['way'].shift())))
                       .groupby(df['date']).cumsum())
    
    print (df)
         date way  journey
    0  date_1   A        1
    1  date_1   B        2
    2  date_1   A        3
    3  date_2   A        1
    4  date_2   A        1
    5  date_2   A        1
    

    【讨论】:

    • 您的第二个解决方案正是我所需要的,谢谢!
    猜你喜欢
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多