将 Pandas 时间戳转换为时间(寻找比 .apply 更快的东西)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33000660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:59:50  来源:igfitidea点击:

Converting Pandas Timestamp to just the time (looking for something faster than .apply)

pythondatetimepandas

提问by SpicyClubSauce

So if I have a timestamp in pandas as such:

因此,如果我在 Pandas 中有这样的时间戳:

Timestamp('2014-11-07 00:05:00')

How can I create a new column that just has the 'time' component?

如何创建一个只有“时间”组件的新列?

So I want

所以我想要

00:05:00

Currently, I'm using .applyas shown below, but this is slow (my dataframe is a couple million rows), and i'm looking for a faster way.

目前,我正在使用.apply如下所示,但这很慢(我的数据帧有几百万行),我正在寻找一种更快的方法。

df['time'] = df['date_time'].apply(lambda x: x.time())

Instead of .apply, I tried using .astype(time), as I noticed .astypeoperations can be faster than .apply, but that apparently doesn't work on timestamps (AttributeError: 'Timestamp' object has no attribute 'astype')... any ideas?

相反.apply,我尝试使用.astype(time),因为我注意到.astype操作可能比 快.apply,但这显然不适用于时间戳(AttributeError: 'Timestamp' object has no attribute 'astype')......有什么想法吗?

回答by chrisb

You want .dt.timesee the docsfor some more examples of things under the .dtaccessor.

您想.dt.time查看文档以了解.dt访问器下的更多示例。

df['date_time'].dt.time