pandas Python:四舍五入到最接近的秒和分钟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/22190638/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Round time to the nearest second and minute
提问by Plug4
I have a DataFramewith a column Timestampwhere each values are the number of seconds since midnight with nanosecond precision. For example:
我有一DataFrame列Timestamp,其中每个值都是自午夜以来的秒数,精度为纳秒。例如:
Timestamp
34200.984537482
34201.395432198
and so on. 34200 seconds since midnight is 9:30:00am.
等等。从午夜开始的 34200 秒是上午 9:30:00。
I would like to create new entries in my dataframewith one column Secondand Minutewhere I round the Timestampto its nearest second and minute (forward looking). So
我想在我dataframe的一列中创建新条目,Second并将Minute其四舍五入Timestamp到最接近的秒和分钟(前瞻性)。所以
Timestamp         Second           Minute
34200.984537482   34201            34260
34201.395432198   34202            34260 
How can I do this in Python? Also, should I use Pandas' DateTimeIndex? Once I round the time, I will compute the time difference between each timestamps so maybe DateTimeIndex is more appropriate. 
我怎样才能在 Python 中做到这一点?另外,我应该使用 PandasDateTimeIndex吗?一旦我舍入时间,我将计算每个时间戳之间的时间差,因此 DateTimeIndex 可能更合适。
回答by Andy Hayden
There is a Series roundmethod:
有一个系列轮方法:
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
I recommend using datetime64 or DatetimeIndex rather than as seconds from midnight... keeping time is hard.
我建议使用 datetime64 或 DatetimeIndex 而不是从午夜开始的秒数......保持时间很难。
One simple way to get a proper datetime column:
获取正确日期时间列的一种简单方法:
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]
回答by willy
For the nearest second, just use the math.ceil, so:
对于最近的一秒钟,只需使用math.ceil,因此:
    import math
    second = math.ceil(timestamp)
For the nearest minute, divide by 60.0, round that, then multiply by 60.
对于最近的一分钟,除以 60.0,四舍五入,然后乘以 60。

