简体   繁体   English

将Pandas DatetimeIndex转换为一年中的分数

[英]Convert Pandas DatetimeIndex to fractional day of year

Is there an easy way to convert a DatetimeIndex to an array of day of years, including a fraction for the hour, minute, etc. components? 是否有一种简单的方法可以将DatetimeIndex转换为年份的数组,包括小时,分钟等组成部分的分数?

For example, converting pd.date_range("2014-01-01 00:00", periods=4, freq="12H") should give me [1.0, 1.5, 2.0, 2.5] . 例如,转换pd.date_range("2014-01-01 00:00", periods=4, freq="12H")应该给我[1.0, 1.5, 2.0, 2.5]

This requires 0.15.0 for the Timedelta functionaility. 对于Timedelta功能,这需要0.15.0。 This will have full precision of your dates. 这将完全精确地记录您的日期。

In [19]: s
Out[19]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2014-01-01 00:00:00, ..., 2014-01-02 12:00:00]
Length: 4, Freq: 12H, Timezone: None

In [21]: s-s[0]
Out[21]: 
<class 'pandas.tseries.tdi.TimedeltaIndex'>
['0 days 00:00:00', ..., '1 days 12:00:00']
Length: 4, Freq: None

In [22]: ((s-s[0]) / pd.Timedelta(1.0,unit='D')) + 1
Out[22]: Float64Index([1.0, 1.5, 2.0, 2.5], dtype='float64')

Dividing by a TimedeltaIndex by a Timedelta gives you a (float) fraction. 用TimedeltaIndex除以Timedelta可得到(浮动)分数。 Dates are 0 based so we add back 1. 日期是从0开始的,因此我们加1。

The above 'assumes' that all of the dates are in the same year. 上述“假设”所有日期都在同一年。 Here is a more robust way to do this (datetimeindex subtraction is not currently directly supported) 这是一种更健壮的方法(当前不直接支持datetimeindex减法)

In [53]: pd.TimedeltaIndex(s.asi8-s.to_period('A').to_timestamp().asi8)
Out[53]: 
<class 'pandas.tseries.tdi.TimedeltaIndex'>
['0 days 00:00:00', ..., '1 days 12:00:00']
Length: 4, Freq: None

I'm not sure if there are builtin methods to achieve this more neatly, but you can do: 我不确定是否有内置方法可以更巧妙地实现此目的,但是您可以执行以下操作:

dr = pd.date_range("2014-01-01 00:00", periods=4, freq="12H")
dr.dayofyear + dr.hour / 24.0
Out[8]: array([ 1. ,  1.5,  2. ,  2.5])

Unfortunately with this approach I think you'll have to create enough terms to get to the precision you want, eg to include minutes it would be: 不幸的是,使用这种方法,我认为您必须创建足够的术语才能达到所需的精度,例如,要包括分钟数:

dr.dayofyear + dr.hour / 24.0 + dr.minute / (24.0 * 60)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM