我有一个 DataFrame有一列 Timestamp其中每个值都是自午夜以来的秒数,精度为纳秒。例如:
Timestamp
34200.984537482
34201.395432198
等等。自午夜以来的 34200 秒是上午 9:30:00。
我想在我的 dataframe 中创建新条目一栏 Second和 Minute我在哪里绕过Timestamp到最接近的秒和分钟(前瞻性)。所以
Timestamp Second Minute
34200.984537482 34201 34260
34201.395432198 34202 34260
我如何在 Python 中执行此操作?另外,我应该使用 Pandas 的 DateTimeIndex 吗? ?计算时间后,我将计算每个时间戳之间的时间差,因此 DateTimeIndex 可能更合适。
请您参考如下方法:
有一个系列 round方法:
In [11]: df.Timestamp.round()
Out[11]:
0 34201
1 34201
Name: Timestamp, dtype: float64
In [12]: df.Timestamp.round(1)
Out[12]:
0 34201.0
1 34201.4
Name: Timestamp, dtype: float64
In [13]: df.Timestamp.round(-1)
Out[13]:
0 34200
1 34200
Name: Timestamp, dtype: float64
我建议使用 datetime64 或 DatetimeIndex 而不是从午夜算起的秒数……保持时间很难。
获取正确日期时间列的一种简单方法:
In [21]: pd.Timestamp('2014-03-04') + df.Timestamp.apply(pd.offsets.Second)
Out[21]:
0 2014-03-04 09:30:00
1 2014-03-04 09:30:01
Name: Timestamp, dtype: datetime64[ns]
