首页 > 解决方案 > 将 UTC 时间字符串的 pandas 数据框列转换为浮点数

问题描述

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

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

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

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'

提前谢谢了。

标签: pythonstringpandasdataframeutc

解决方案


我认为您可以使用to_datetimewith 参数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

推荐阅读