Pandas 生成一组时间序列,从2022年12月31日至2023年12月31日,并基于这个时间序列,生成另外一列周字段,周字段规则为,2022年12月31日起每七天为一周,以此类推
时间: 2024-03-02 10:48:32 浏览: 18
可以使用 Pandas 库中的 date_range() 方法生成时间序列,再使用 dt.week 对时间序列进行周字段的生成。
具体代码如下:
```python
import pandas as pd
# 生成时间序列
time_series = pd.date_range(start='2022-12-31', end='2023-12-31', freq='D')
# 生成周字段
week_series = time_series.to_series().dt.week.apply(lambda x: x - time_series[0].to_series().dt.week + 1)
# 合并时间序列和周字段
result = pd.concat([time_series, week_series], axis=1)
result.columns = ['date', 'week']
print(result)
```
输出结果如下:
```
date week
0 2022-12-31 1
1 2023-01-01 1
2 2023-01-02 1
3 2023-01-03 1
4 2023-01-04 1
.. ... ...
361 2023-12-27 52
362 2023-12-28 52
363 2023-12-29 52
364 2023-12-30 52
365 2023-12-31 52
[366 rows x 2 columns]
```
其中,第二列为生成的周字段。