gpt4 book ai didi

python - Groupby、Shift 和 Sum

转载 作者:太空宇宙 更新时间:2023-11-04 04:07:39 25 4
gpt4 key购买 nike

我有以下数据框:

product    Week_Number       Sales
1 1 10
2 1 15
1 2 20

我想按产品和周数分组,并创建一个包含该产品下周销售额的列:

product    Week_Number       Sales       next_week
1 1 10 20
2 1 15 0
1 2 20 0

最佳答案

使用DataFrame.sort_valuesDataFrameGroupBy.shift :

#if not sure if sorted per 2 columns
df = df.sort_values(['product','Week_Number'])

#pandas 0.24+
df['next_week'] = df.groupby('product')['Sales'].shift(-1, fill_value=0)
#pandas below
#df['next_week'] = df.groupby('product')['Sales'].shift(-1).fillna(0, downcast='int')
print (df)
product Week_Number Sales next_week
0 1 1 10 20
1 2 1 15 0
2 1 2 20 0

如果可能重复并需要先在真实数据中聚合sum:

df = df.groupby(['product','Week_Number'], as_index=False)['Sales'].sum()
df['next_week'] = df.groupby('product')['Sales'].shift(-1).fillna(0, downcast='int')
print (df)
product Week_Number Sales next_week
0 1 1 10 20
1 1 2 20 0
2 2 1 15 0

关于python - Groupby、Shift 和 Sum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56948702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com