Skip to main content
 首页 » 编程设计

python-2.7之Pandas -Python 2.7 : How convert timeseries index to seconds of the day

2024年12月31日8xing901022

我正在尝试将时间序列索引转换为一天中的秒数,即随着时间的推移,秒数从 0-86399 增加。我目前可以恢复一天中的时间,但无法以矢量化方式将其转换为秒数:

df['timeofday'] = df.index.time 

有什么想法吗?谢谢。

请您参考如下方法:

正如@Jeff 指出的那样,我原来的回答误解了你在做什么。但是以下应该可以工作并且它是矢量化的。我的答案依赖于 numpy datetime64 操作(从当前 datetime64 中减去一天的开始,然后用 timedelta64 进行划分以获得秒数) :

>>> df 
 
                            A 
2011-01-01 00:00:00 -0.112448 
2011-01-01 01:00:00  1.006958 
2011-01-01 02:00:00 -0.056194 
2011-01-01 03:00:00  0.777821 
2011-01-01 04:00:00 -0.552584 
2011-01-01 05:00:00  0.156198 
2011-01-01 06:00:00  0.848857 
2011-01-01 07:00:00  0.248990 
2011-01-01 08:00:00  0.524785 
2011-01-01 09:00:00  1.510011 
2011-01-01 10:00:00 -0.332266 
2011-01-01 11:00:00 -0.909849 
2011-01-01 12:00:00 -1.275335 
2011-01-01 13:00:00  1.361837 
2011-01-01 14:00:00  1.924534 
2011-01-01 15:00:00  0.618478 
 
df['sec'] = (df.index.values 
            - df.index.values.astype('datetime64[D]'))/np.timedelta64(1,'s') 
 
                            A      sec 
2011-01-01 00:00:00 -0.112448        0 
2011-01-01 01:00:00  1.006958     3600 
2011-01-01 02:00:00 -0.056194     7200 
2011-01-01 03:00:00  0.777821    10800 
2011-01-01 04:00:00 -0.552584    14400 
2011-01-01 05:00:00  0.156198    18000 
2011-01-01 06:00:00  0.848857    21600 
2011-01-01 07:00:00  0.248990    25200 
2011-01-01 08:00:00  0.524785    28800 
2011-01-01 09:00:00  1.510011    32400 
2011-01-01 10:00:00 -0.332266    36000 
2011-01-01 11:00:00 -0.909849    39600 
2011-01-01 12:00:00 -1.275335    43200 
2011-01-01 13:00:00  1.361837    46800 
2011-01-01 14:00:00  1.924534    50400 
2011-01-01 15:00:00  0.618478    54000