我已经看到多个关于如何定义自己的函数来执行与此类似的操作的问题,但我不知道如何使用 timedelta 的内置函数。有没有人有使用 timedelta.round() 的例子?我有 timedelta 对象,我想四舍五入到最接近的全天。
文档位于 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timedelta.round.html是:
Timedelta.round
Round the Timedelta to the specified resolution
Parameters:
freq : a freq string indicating the rounding resolution
Returns: a new Timedelta rounded to the given resolution of
freq
Raises: ValueError if the freq cannot be converted
最佳答案
这个问题已经回答了,但我把它放在一个 MWE 中以便更好地理解:
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):
关于python - 使用 timedelta.round() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51661280/