使用timedelta.round()函数 [英] using the timedelta.round() function
问题描述
我已经看到关于如何定义自己的函数的多个问题,这些函数可以执行类似的操作,但是我无法弄清楚如何使用timedelta的内置函数.有没有人有使用timedelta.round()的示例?我有一些timedelta对象,我想四舍五入到最接近的全天.
I've seen multiple questions asked on how to define your own function that does things similar to this, but I can't figure out how to use timedelta's built in function. Does anyone have an example of a use of timedelta.round()? I have timedelta objects that I want to round to the closest full-day.
文档位于 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timedelta.round.html 是:
Timedelta.round
Timedelta.round
将Timedelta调整为指定的分辨率
Round the Timedelta to the specified resolution
参数:
freq:表示舍入分辨率的频率字符串
freq : a freq string indicating the rounding resolution
返回:新的Timedelta舍入为给定分辨率的 freq
Returns: a new Timedelta rounded to the given resolution of freq
提高:如果无法转换频率,则会引发ValueError
Raises: ValueError if the freq cannot be converted
推荐答案
这个问题已经回答了,但是为了更好的理解,我把它设为了MWE:
This question is already answered, but I put it a MWE in for better understanding:
import pandas as pd
df = pd.Series(pd.to_timedelta([
'0 days +01:01:02.123',
'0 days +04:03:04.651']))
df.dt.round('5s') #Rounds to 5sec
输出为:
0 01:01:00
1 04:03:05
dtype: timedelta64[ns]
其他有用且相关的问题(timedelta的用法与datetime相似):
Other useful and connected question (timedelta is similar in usage to datetime):
这篇关于使用timedelta.round()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!