看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)运营部拿到了 2024-08-01 ~ 2024-08-30 共 30 天的每日销售额:
import pandas as pd
import numpy as np
# 30 天日期 + 随机销售额
rng = pd.date_range('2024-08-01', periods=30, freq='D')
sales = pd.Series(np.random.randint(800, 2000, 30),
index=rng, name='日销售额')
任务:
Period
索引,并计算 每周总销售额。Period[W]
。代码如下:
(
sales.to_period('W')
.groupby(level=0)
.sum()
)
'''
2024-07-29/2024-08-04 6210
2024-08-05/2024-08-11 9277
2024-08-12/2024-08-18 10453
2024-08-19/2024-08-25 9468
2024-08-26/2024-09-01 5819
Freq: W-SUN, Name: 日销售额, dtype: int64
'''
将索引的日期范围修改为「年份-周数」形式:
(
sales.to_period('W')
.pipe(lambda x: x.set_axis(x.index.strftime('%G-W%V')))
.groupby(level=0)
.sum()
)
(完)
更新时间:2025-08-20 14:21:48 标签:pandas python 周期 销售额