我正在使用一个有20个Id的数据框架,对于每个Id,大约有3个商店,每个商店至少每周有3次销售和价格弹性。
数据:
data =
ID STORE WEEK_NUM Price_elasticity
100001 1 1 0.5
100001 1 2 0.5
100001 1 3 0.5
100001 2 1 0.5
100001 2 2 0.9
100001 2 3 0.6
100002 1 1 0.3
100002 1 2 0.3
100002 1 3 0.3
100002 2 1 0.8
100002 2 2 0.8
100002 2 3 0.5问题:
我想找出每一个项目的几个星期
我的尝试:
dft = data.groupby(['ID','STORE']).agg({'Price_Elasticity':'nunique','WEEK_NUM':'count'})
dft = dft.reset_index()
dft = dft[dft['Price_Elasticity'] <= 1]
dft预期结果:
ID STORE WEEK_NUM Price_elasticity
100001 1 1 0.5
100001 1 2 0.5
100001 1 3 0.5
100002 1 1 0.3
100002 1 2 0.3
100002 1 2 0.3
100002 2 1 0.8
100002 2 2 0.8发布于 2022-02-15 16:34:46
考虑合并到值计数数据帧,并返回计数大于1的任何值:
value_counts_df = (
df.groupby(["ID", "STORE"])["Price_elasticity"]
.value_counts()
.rename("value_count")
.to_frame()
.reset_index()
)
df = (
df.merge(
value_counts_df,
on = ["ID", "STORE", "Price_elasticity"]
).query("value_count > 1")
.drop(["value_count"], axis="columns")
.reset_index(drop=True)
)
df
ID STORE WEEK_NUM Price_elasticity
0 100001 1 1 0.5
1 100001 1 2 0.5
2 100001 1 3 0.5
3 100002 1 1 0.3
4 100002 1 2 0.3
5 100002 1 3 0.3
6 100002 2 1 0.8
7 100002 2 2 0.8https://stackoverflow.com/questions/71115955
复制相似问题