将 UTC 时间字符串的 Pandas 数据帧列转换为浮点数 [英] Convert pandas dataframe column of UTC time string to floats

查看:43
本文介绍了将 UTC 时间字符串的 Pandas 数据帧列转换为浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一列字符串的 Pandas 数据框,日期时间为 UTC 格式,但需要将它们转换为浮点数.我很难做到这一点.这是我的专栏的视图:

I have a pandas dataframe with a column of strings, with datetimes in UTC format, but need to convert them to floats. I'm having trouble doing this. Here is a view of my column:

df['time'][0:3]

0    2018-04-18T19:00:00.000000000Z
1    2018-04-18T19:15:00.000000000Z
2    2018-04-18T19:30:00.000000000Z
Name: time, dtype: object

我一直在尝试这个,但对我不起作用:

I've been trying this, but isn't working for me:

import datetime
for i in range(1,len(df)):
        df['time'][i] = datetime.datetime.strptime(df['time'][i], '%Y-%m-%dT%H:%M:%S.%f000Z')

这是我要修复的错误:

execfile(filename, namespace)

exec(compile(f.read(), filename, 'exec'), namespace)

unsup.fit(np.reshape(df,(-1,df.shape[1])))

X = _check_X(X, self.n_components)

X = check_array(X, dtype=[np.float64, np.float32])

array = np.array(array, dtype=dtype, order=order, copy=copy)

ValueError: could not convert string to float: '2018-06-29T20:45:00.000000000Z'

非常感谢.

推荐答案

我认为你可以使用 to_datetime 带参数 format:

df['time1'] = pd.to_datetime(df['time'], format='%Y-%m-%dT%H:%M:%S.%f000Z')
print (df)
                             time               time1
0  2018-04-18T19:00:00.000000000Z 2018-04-18 19:00:00
1  2018-04-18T19:15:00.000000000Z 2018-04-18 19:15:00
2  2018-04-18T19:30:00.000000000Z 2018-04-18 19:30:00

对于分配回来:

df['time'] = pd.to_datetime(df['time'], format='%Y-%m-%dT%H:%M:%S.%f000Z')
print (df)
                 time
0 2018-04-18 19:00:00
1 2018-04-18 19:15:00
2 2018-04-18 19:30:00

这篇关于将 UTC 时间字符串的 Pandas 数据帧列转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆