2017-09-13 93 views
1

我有微秒,我想从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() takes no keyword arguments如何从timedelta删除微秒

例如:我想00:19:58.582052成为0点19分58秒或00:19:58.58

enter image description here

+0

你应该考虑改变你的数据timedelta或时间戳(如果你有日期一起)从字符串。没有很好的理由把它保留为字符串。然后,你可以使用'floor'方法优秀的'dt'来截断。看到我的答案。 –

回答

0

how_long_it_took_to_order列似乎是字符串(object)D型的。

那么试试这个:

analyze_me['how_long_it_took_to_order'] = \ 
    analyze_me['how_long_it_took_to_order'].str.split('.').str[0] 

或:

analyze_me['how_long_it_took_to_order'] = \ 
    analyze_me['how_long_it_took_to_order'].str.replace('(\.\d{2})\d+', r'\1') 

为 “厘”,如:00:19:58.58

+0

看起来它会完全删除小数部分。 – pvg

+0

@pvg,是的,这就是我的理解:'我想要00:19:58.582052成为00:19:58或00:19:58.58' – MaxU

+0

这有点含糊,但标题说'微秒'。字符串的第二个版本是没​​有微秒的(第100版)。 – pvg

3

我认为你需要将字符串转换到一个timedelta与pd.to_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 

在这里,我创造了一些timedeltas的一个系列,然后使用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] 
+2

如果他有字符串,那很好。只需将其转换为timedelta即可。字符串长度将是可变的,但timedelta是准确的 –

+1

这似乎是一个更为理智的答案,而不是消除字符串。 – pvg

+0

我认为这个解决方案不能正常工作,因为OP有两个字符串只代表时间和日期+时间 - 如下所示:'pd.to_timedelta(['00:19:58.582052','2014-10-26 13:51: 59.898924'])' - 这将不起作用... – MaxU