gpt4 book ai didi

python - 我如何抵消 Pandas dayofyear 以便开始日期是 10 月 1 日而不是 1 月 1 日?

转载 作者:行者123 更新时间:2023-12-05 06:12:23 24 4
gpt4 key购买 nike

我有以下数据框:

我如何抵消 Pandas dayofyear 以便开始日期是 10 月 1 日而不是 1 月 1 日

enter image description here

在这种情况下,我希望年份是从 10 月 1 日到 9 月 30 日,并且需要考虑闰年。

下面是我想要输出的示例,其中日期列是唯一的变量。

enter image description here

这是表格形式的数据框:

           Day  stock  dayofyear  weekday  month  year  leapyear
0 24/09/2019 10 267 1 9 2019 False
1 25/09/2019 10 268 2 9 2019 False
2 26/09/2019 11 269 3 9 2019 False
3 27/09/2019 12 270 4 9 2019 False
4 28/09/2019 14 271 5 9 2019 False
5 29/09/2019 14 272 6 9 2019 False
6 30/09/2019 15 273 0 9 2019 False
7 01/10/2019 16 274 1 10 2019 False
8 02/10/2019 17 275 2 10 2019 False
9 03/10/2019 18 276 3 10 2019 False
10 04/10/2019 19 277 4 10 2019 False

最佳答案

使用:

df['Day'] = pd.to_datetime(df['Day'], dayfirst=True)

base_year = np.where(df['month'].ge(10), df['year'], df['year'].sub(1))
base_date = pd.to_datetime(base_year, format='%Y') + pd.DateOffset(months=9)
df['dayofyear'] = (df['Day'] - base_date).dt.days.add(1)

详细信息:

使用 pd.to_datetimeDay 列转换为 pandas 日期时间系列,然后使用 np.where连同 Series.gtSeries.subDay 列中的每个日期计算 base_year

print(base_year)
array([2018, 2018, 2018, 2018, 2018, 2018, 2018, 2019, 2019, 2019, 2019])

使用pd.to_datetimebase_year 转换为 pandas 日期时间系列并添加 9 个月 的偏移量,以便 base_date10 月 1 日开始.

print(base_date)
DatetimeIndex(['2018-10-01', '2018-10-01', '2018-10-01', '2018-10-01',
'2018-10-01', '2018-10-01', '2018-10-01', '2019-10-01',
'2019-10-01', '2019-10-01', '2019-10-01'],
dtype='datetime64[ns]', freq=None)

从这个 base_date 中减去 Day 列并使用 Series.dt.days计算 dayofyear:

print(df)
Day stock dayofyear weekday month year leapyear
0 2019-09-24 10 359 1 9 2019 False
1 2019-09-25 10 360 2 9 2019 False
2 2019-09-26 11 361 3 9 2019 False
3 2019-09-27 12 362 4 9 2019 False
4 2019-09-28 14 363 5 9 2019 False
5 2019-09-29 14 364 6 9 2019 False
6 2019-09-30 15 365 0 9 2019 False
7 2019-10-01 16 1 1 10 2019 False
8 2019-10-02 17 2 2 10 2019 False
9 2019-10-03 18 3 3 10 2019 False
10 2019-10-04 19 4 4 10 2019 False

关于python - 我如何抵消 Pandas dayofyear 以便开始日期是 10 月 1 日而不是 1 月 1 日?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63644970/

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