将 UTC 时间字符串的 pandas 数据帧列转换为浮点数

Convert pandas dataframe column of UTC time string to floats

我有一个 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'

非常感谢。

我想你可以使用 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