python - 将 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'
提前谢谢了。
解决方案
我认为您可以使用to_datetime
with 参数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
推荐阅读
- dart - Flutter:任何人都可以帮助在 Flutter 中制作自定义 TabController 吗?
- mysql - 如何在 Laravel SQL 查询中同时使用 `GroupBy` 和 `join`
- google-cloud-platform - 快照大小不一致
- sql - 为新恢复的数据库自动更改链接服务器名称
- c# - Lync-SDK MissingMethod-异常
- arrays - Swift 扩展仅适用于具有目标 c 元素的 Array 可能吗?
- awk - Grep 模式并在匹配模式之后选择 a 的一部分
- java - 如何在 java 中将字符串化的 JSONObject[] 转换为 JSONObj[]
- javascript - 如何在鼠标滚动和右键单击时添加事件?
- c# - foreach 语句不能运行?