我想从 pandas 列中截断微秒。我尝试了类似 analyze_me['how_long_it_took_to_order'] = analyze_me['how_long_it_took_to_order'].apply(lambda x: x.replace(microsecond=0)
但是出现了这个错误 replace()不接受关键字参数
。
例如:我希望 00:19:58.582052 变成 00:19:58 或 00:19:58.58
最佳答案
我认为您需要使用 pd.to_timedelta
将您的字符串转换为 timedelta,然后利用基于字符串截断的 floor 方法的优秀 dt 访问器。这是您数据的前两行。
df['how_long_it_took_to_order'] = pd.to_timedelta(df['how_long_it_took_to_order'])
df['how_long_it_took_to_order'].dt.floor('s')
0 00:19:58
1 00:25:09
可以四舍五入到百分之一秒。
df['how_long_it_took_to_order'].dt.floor('10ms')
0 00:19:58.580000
1 00:25:09.100000
在这里,我创建了一些时间增量系列,然后使用 dt
访问器和 floor
方法来截断到最接近的微秒。
d = pd.timedelta_range(0, periods=6, freq='644257us')
s = pd.Series(d)
s
0 00:00:00
1 00:00:00.644257
2 00:00:01.288514
3 00:00:01.932771
4 00:00:02.577028
5 00:00:03.221285
dtype: timedelta64[ns]
现在截断
s.dt.floor('s')
0 00:00:00
1 00:00:00
2 00:00:01
3 00:00:01
4 00:00:02
5 00:00:03
dtype: timedelta64[ns]
如果您想截断到最接近的百分之一秒,请执行以下操作:
s.dt.floor('10ms')
0 00:00:00
1 00:00:00.640000
2 00:00:01.280000
3 00:00:01.930000
4 00:00:02.570000
5 00:00:03.220000
dtype: timedelta64[ns]
关于python - 如何从 timedelta 中删除微秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46204241/