【问题标题】:Convert pandas dataframe column of UTC time string to floats将 UTC 时间字符串的 pandas 数据框列转换为浮点数
【发布时间】:2018-06-30 06:25:00
【问题描述】:

我有一个带有一列字符串的 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'

提前非常感谢。

【问题讨论】:

    标签: python string pandas dataframe utc


    【解决方案1】:

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

    【讨论】:

    • 谢谢,忘记了基本的熊猫东西。 'pd.to_numeric(df['time'])' 是我要找的。​​span>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 2022-01-14
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多