我有一个pandas.DatetimeIndex,例如:
pd.date_range('2012-1-1 02:03:04.000',periods=3,freq='1ms')
>>> [2012-01-01 02:03:04, ..., 2012-01-01 02:03:04.002000]我想将日期(Timestamps)舍入到最接近的秒。我该怎么做?预期结果类似于:
[2012-01-01 02:03:04.000000, ..., 2012-01-01 02:03:04.000000]是否可以在不更改dtype [ns]的情况下,通过将Numpy datetime64[ns]舍入到秒数来实现这一点
np.array(['2012-01-02 00:00:00.001'],dtype='datetime64[ns]')发布于 2012-12-09 22:28:02
更新:如果要对DatetimeIndex / datetime64列执行此操作,更好的方法是直接使用np.round,而不是通过应用/映射:
np.round(dtindex_or_datetime_col.astype(np.int64), -9).astype('datetime64[ns]')旧的答案(还有更多的解释):
虽然@Matti的答案显然是处理你的情况的正确方法,但我想我应该添加一个答案,如何将时间戳舍入到最接近的秒数:
from pandas.lib import Timestamp
t1 = Timestamp('2012-1-1 00:00:00')
t2 = Timestamp('2012-1-1 00:00:00.000333')
In [4]: t1
Out[4]: <Timestamp: 2012-01-01 00:00:00>
In [5]: t2
Out[5]: <Timestamp: 2012-01-01 00:00:00.000333>
In [6]: t2.microsecond
Out[6]: 333
In [7]: t1.value
Out[7]: 1325376000000000000L
In [8]: t2.value
Out[8]: 1325376000000333000L
# Alternatively: t2.value - t2.value % 1000000000
In [9]: long(round(t2.value, -9)) # round milli-, micro- and nano-seconds
Out[9]: 1325376000000000000L
In [10]: Timestamp(long(round(t2.value, -9)))
Out[10]: <Timestamp: 2012-01-01 00:00:00>因此,您可以将此应用于整个索引:
def to_the_second(ts):
return Timestamp(long(round(ts.value, -9)))
dtindex.map(to_the_second)发布于 2016-09-04 03:02:04
在pandas 0.18.0中为DatetimeIndex、Timestamp、TimedeltaIndex和Timedelta添加了round()方法。现在我们可以执行以下操作:
In[114]: index = pd.DatetimeIndex([pd.Timestamp('2012-01-01 02:03:04.000'), pd.Timestamp('2012-01-01 02:03:04.002'), pd.Timestamp('20130712 02:03:04.500'), pd.Timestamp('2012-01-01 02:03:04.501')])
In[115]: index.values
Out[115]:
array(['2012-01-01T02:03:04.000000000', '2012-01-01T02:03:04.002000000',
'2013-07-12T02:03:04.500000000', '2012-01-01T02:03:04.501000000'], dtype='datetime64[ns]')
In[116]: index.round('S')
Out[116]:
DatetimeIndex(['2012-01-01 02:03:04', '2012-01-01 02:03:04',
'2013-07-12 02:03:04', '2012-01-01 02:03:05'],
dtype='datetime64[ns]', freq=None)round()接受频率参数。它的字符串别名在here中列出。
发布于 2012-12-09 22:17:11
更改索引本身几乎没有什么意义-因为您可以像您的问题中那样,使用带有所需频率参数的date_range进行生成。
我假设您要做的是更改包含数据的时间序列的频率,在这种情况下,您可以使用resample (documentation)。例如,如果您有以下时间序列:
dt_index = pd.date_range('2012-1-1 00:00.001',periods=3, freq='1ms')
ts = pd.Series(randn(3), index=dt_index)
2012-01-01 00:00:00 0.594618
2012-01-01 00:00:00.001000 0.874552
2012-01-01 00:00:00.002000 -0.700076
Freq: L然后,您可以使用重采样将频率更改为秒,指定如何聚合这些值(平均值、总和等):
ts.resample('S', how='sum')
2012-01-01 00:00:00 0.594618
2012-01-01 00:00:01 0.174475
Freq: Shttps://stackoverflow.com/questions/13785932
复制相似问题