pandas 中的半小时四舍五入
pandas 中的 round() 函数将时间 07:30 向下舍入到 07:00 但我想对超过 30 分钟(含)的任何时间进行舍入。
例如。
07:15 to 07:00
05:25 to 05:00
22:30 to 23:00
18:45 to 19:00
如何使用 pandas 对数据框的列实现此目的?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
拥有 2025-01-27 22:30:28
这里是与时间戳合作的版本:
#dummy data:
df = pd.DataFrame({'time':pd.to_datetime([np.random.randint(0,10**8) for a in range(10)], unit='s')})
def custom_round(df, col, out):
if df[col].minute >= 30:
df[out] = df[col].ceil('H')
else:
df[out] = df[col].floor('H')
return df
df.apply(lambda x: custom_round(x, 'time', 'new_time'), axis=1)
#edit:
使用numpy:
def custom_round(df, col, out):
df[out] = np.where(
(
df['time'].dt.minute>=30),
df[col].dt.ceil('H'),
df[col].dt.floor('H')
)
return df
df = custom_round(df, 'time', 'new_time')
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
时间戳
您需要使用
dt.round< /代码>
。然而,这有点像前一小时/下一小时的行为取决于该小时本身。您可以通过添加或减去少量时间(此处为 1ns)来强制它:
浮动
IIUC,您可以使用
divmod
(或 "="">numpy.modf
) 获取整数和小数部分,然后执行简单的布尔运算:替代方案:使用 "="">
numpy.modf
) 获取整数和小数部分,然后执行简单的布尔算术: pydata.org/docs/reference/api/pandas.Series.mod.html" rel="nofollow noreferrer">mod
和 boolean 到 int 等价:输出:
注意 精确。由于浮点运算,比较浮点数并不总是那么容易。例如,使用
gt
在 22.30 上会失败。为了确保精度首先四舍五入到 2 位数字。或使用整数:
timestamps
You need to use
dt.round
. This is however a bit as the previous/next hour behavior depends on the hour itself. You can force it by adding or subtracting a small amount of time (here 1ns):floats
IIUC, you can use
divmod
(ornumpy.modf
) to get the integer and decimal part, then perform simple boolean arithmetic:Alternative: using
mod
and boolean to int equivalence:output:
Note on precision. It is not always easy to compare floats due to floating point arithmetics. For instance using
gt
would fail on the 22.30 here. To ensure precision round to 2 digits first.or use integers: