python - 多列上的 Pandas cumsum + cumcount

标签 python pandas

阿罗哈,

我有以下数据框

stores = [1,2,3,4,5]
weeks = [1,1,1,1,1]
df = pd.DataFrame({'Stores' : stores,
                  'Weeks' : weeks})

df = pd.concat([df]*53)
df['Weeks'] = df['Weeks'].add(df.groupby('Stores').cumcount())

df['Target'] = np.random.randint(400,600,size=len(df)) 
df['Actual'] = np.random.randint(350,800,size=len(df)) 
df['Variance %'] = (df['Target'] - df['Actual']) / df['Target']
df.loc[df['Variance %'] >= 0.01, 'Status'] = 'underTarget'
df.loc[df['Variance %'] <= 0.01, 'Status'] = 'overTarget'
df['Status'] = df['Status'].fillna('atTarget')

df.sort_values(['Stores','Weeks'],inplace=True)

这给了我以下内容

打印(df.head())

    Stores  Weeks   Target  Actual  Variance %  Status
0   1   1   430 605 -0.406977   overTarget
0   1   2   549 701 -0.276867   overTarget
0   1   3   471 509 -0.080679   overTarget
0   1   4   549 378 0.311475    underTarget
0   1   5   569 708 -0.244288   overTarget
0   1   6   574 650 -0.132404   overTarget
0   1   7   466 623 -0.336910   overTarget

现在我想做的是对超出或低于目标的商店进行累积计数,但在状态更改时重置。

我认为这将是执行此操作的最佳方法(以及此方法的许多变体),但这不会重置计数器。

s = df.groupby(['Stores','Weeks','Status'])['Status'].shift().ne(df['Status'])
df['Count'] = s.groupby(df['Stores']).cumsum()

我的逻辑是按相关列进行分组,然后执行 != 移位来重置累积和

当然,我已经搜索了很多不同的问题,但我似乎无法弄清楚这一点。有人愿意向我解释解决这个问题的最佳方法是什么吗?

我希望这里的一切都是清晰且可重现的。如果您需要任何其他信息,请告诉我。

预期输出

  Stores    Weeks   Target  Actual  Variance %  Status Count
0   1   1   430 605 -0.406977   overTarget             1
0   1   2   549 701 -0.276867   overTarget             2
0   1   3   471 509 -0.080679   overTarget             3
0   1   4   549 378 0.311475    underTarget            1  # Reset here as status changes
0   1   5   569 708 -0.244288   overTarget             1  # Reset again.
0   1   6   574 650 -0.132404   overTarget             2
0   1   7   466 623 -0.336910   overTarget             3

最佳答案

通过cumsum创建 key 后尝试pd.Series.groupby()

s=df.groupby('Stores')['Status'].apply(lambda x : x.ne(x.shift()).ne(0).cumsum())
df['Count']=df.groupby([df.Stores,s]).cumcount()+1

关于python - 多列上的 Pandas cumsum + cumcount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55494872/

相关文章:

python - 计算 pandas 中先前找到的重复项的数量

python - 基于 'date' 列的月份和年份的列值

python - 为什么在编译时确定位置?

python - python中的运算符重载,对象位于运算符的右侧

python - 将类似日期时间的对象传递给 seaborn.lmplot

python - Pandas 样式格式不将列格式化为带小数位的百分比

python - 在 Pandas 数据框中保留大小为 1 >= k 的 block

python - 使用 pdsh 通过 linux 解析内联 python 命令

python - Python 'for' 循环中的作用域

python - 异常必须派生自 BaseException