gpt4 book ai didi

python - Pandas date_range 和闰年

转载 作者:行者123 更新时间:2023-11-28 17:43:42 29 4
gpt4 key购买 nike

运行这段代码时:

a = pd.date_range("1959-12-09 00:00:00", "2013-12-09 12:00:00", freq = "365D6H")
weekDays = [dt.datetime.weekday(d) for d in a]
df = pd.DataFrame({"Date": a, "Jour": weekDays})
df.head(6)

我得到:

0 1959-12-09 00:00:00     2
1 1960-12-08 06:00:00 3 *
2 1961-12-08 12:00:00 4
3 1962-12-08 18:00:00 5
4 1963-12-09 00:00:00 0
5 1964-12-08 06:00:00 1 *
6 1965-12-08 12:00:00 2

等等有关闰年的问题。尽管有闰年,我怎样才能使日期之间恰好有一个日历年?

最佳答案

除了使用 date_range,您还可以使用列表理解来创建它:

In [11]: pd.to_datetime(["%s-12-09 %s:00:00" % (y, (6 * h) % 24)
for h, y in enumerate(xrange(1959, 2014))])
Out[11]:
<class 'pandas.tseries.index.DatetimeIndex'>
[1959-12-09 00:00:00, ..., 2013-12-09 12:00:00]
Length: 55, Freq: None, Timezone: None

频率为无,因为这不是常规频率...如果您尝试添加一个 numpy 年份和一个 numpy 小时,您将看到:

In [21]: np.timedelta64(1, 'Y') + np.timedelta64(6, 'h')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-6a7f3e5b3315> in <module>()
----> 1 np.timedelta64(1, 'Y') + np.timedelta64(6, 'h')

TypeError: Cannot get a common metadata divisor for NumPy datetime metadata [Y] and [h] because they have incompatible nonlinear base time units

关于python - Pandas date_range 和闰年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20958505/

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