gpt4 book ai didi

Pandas ,按周分组数据

转载 作者:行者123 更新时间:2023-12-01 04:34:47 27 4
gpt4 key购买 nike

一年大约有 54 周。

我想获得每个弱势群体的销售额总和。

给定一个时间序列数据(带datetime或unixtime)(我的数据看起来像:

 userId,movieId,rating,timestamp
1,31,2.5,1260759144

)

我希望输出看起来像下面这样

1week (1/1 - 1/7) : 30$
2week (1/8 - 1/14) : 40$
...
54week (12/24 - 12/31) : 50$

我输入的日期(1/1 等)只是为了解释,我想获得每周组(以获得季节性索引),并且不必从 1/1 或类似的东西..

数据可能包含多个年份。

  • 编辑

我想在多年内按周进行分组,就像您可以在多年内按月 [1 月、2 月、..... 12 月] 进行分组(12 组用于多年数据)。

最佳答案

使用Series.resampleweek 和聚合函数 - 例如按 mean:

rng = pd.date_range('2017-04-03', periods=10)
s = pd.DataFrame({'a': range(10)},index=rng)['a']
print (s)
2017-04-03 0
2017-04-04 1
2017-04-05 2
2017-04-06 3
2017-04-07 4
2017-04-08 5
2017-04-09 6
2017-04-10 7
2017-04-11 8
2017-04-12 9
Freq: D, Name: a, dtype: int64

s1 = s.resample('W').mean()
#alternative
#s1 = s.groupby(pd.Grouper(freq='W')).mean()
print (s1)
2017-04-09 3
2017-04-16 8
Freq: W-SUN, Name: a, dtype: int64

备选方案:

s1 = s.groupby(s.index.strftime('%Y-%U')).mean()
print (s1)
2017-14 2.5
2017-15 7.5
Name: a, dtype: float64

编辑:

带有样本数据需要预处理:

print (df)
userId movieId rating timestamp
0 1 31 2.5 1260759144
1 1 31 2.5 1560759144


df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s')

w = df['timestamp'].rename('week').dt.weekofyear
df = df['rating'].groupby(w).mean().reset_index(name='val')
print (df)
week val
0 25 2.5
1 51 2.5

关于 Pandas ,按周分组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55207590/

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