pandas 熊猫 - 将时间对象更改为浮点数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28353218/
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
pandas - change time object to a float?
提问by trench
I have a field for call length in my raw data which is listed as an object, such as: 00:10:30 meaning 10 minutes and 30 seconds. How can I convert this to a number like 10.50?
我的原始数据中有一个用于调用长度的字段,它被列为一个对象,例如:00:10:30 表示 10 分 30 秒。如何将其转换为 10.50 之类的数字?
I keep getting errors. If convert the fields with pd.datetime then I can't do an .astype('float'). In Excel, I just multiple the time stamp by 1440 and it outputs the number value I want to work with. (Timestamp * 24 * 60)
我不断收到错误。如果使用 pd.datetime 转换字段,那么我无法执行 .astype('float')。在 Excel 中,我只是将时间戳乘以 1440,它会输出我想要使用的数值。(时间戳 * 24 * 60)
回答by Andy Hayden
You can use time deltasto do this more directly:
您可以使用时间增量更直接地执行此操作:
In [11]: s = pd.Series(["00:10:30"])
In [12]: s = pd.to_timedelta(s)
In [13]: s
Out[13]:
0 00:10:30
dtype: timedelta64[ns]
In [14]: s / pd.offsets.Minute(1)
Out[14]:
0 10.5
dtype: float64
回答by EdChum
I would convert the string to a datetime and then use the dtaccessor to access the components of the time and generate your minutes column:
我会将字符串转换为日期时间,然后使用dt访问器访问时间的组成部分并生成您的分钟列:
In [16]:
df = pd.DataFrame({'time':['00:10:30']})
df['time'] = pd.to_datetime(df['time'])
df['minutes'] = df['time'].dt.hour * 60 + df['time'].dt.minute + df['time'].dt.second/60
df
Out[16]:
time minutes
0 2015-02-05 00:10:30 10.5
回答by Liam Foley
There is probably a better way of doing this, but this will work.
可能有更好的方法来做到这一点,但这会奏效。
from datetime import datetime
import numpy as np
my_time = datetime.strptime('00:10:30','%H:%M:%S')
zero_time = datetime.strptime('00:00:00','%H:%M:%S')
x = my_time - zero_time
x.seconds
Out[25]: 630

