熊猫date_range和闰年

时间:2014-01-06 20:17:15

标签: python pandas date-range leap-year

运行此代码时:

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
闰年出现了问题。 尽管闰年,我怎么能在日期之间只有一个日历年呢?

1 个答案:

答案 0 :(得分: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