python - 如何将包含“4:20”等字符串的列中的数据转换为浮点数
问题描述
在我的数据框中,有一列包含如下值:
PowerPlayTimeOnIce
0:05
0:05
1:24
3:29
1:34
0
0:05
0
0
如何将这些转换为浮点数?
此方法无效:
df["powerPlayTimeOnIce"] = df["powerPlayTimeOnIce"].astype('float')
编辑:更新数据示例以更好地适应问题
解决方案
使用to_datetime
s=pd.to_datetime(df.PowerPlayTimeOnIce,format='%M:%S')
s.dt.minute*60+s.dt.second
Out[881]:
0 5
1 5
2 84
3 209
4 94
5 5
Name: PowerPlayTimeOnIce, dtype: int64
更新
s=pd.to_datetime(df.PowerPlayTimeOnIce,format='%M:%S',errors='coerce')
(s.dt.minute*60+s.dt.second).fillna(0)
Out[886]:
0 5.0
1 5.0
2 84.0
3 209.0
4 94.0
5 5.0
6 0.0
Name: PowerPlayTimeOnIce, dtype: float64
数据输入
PowerPlayTimeOnIce
0 0:05
1 0:05
2 1:24
3 3:29
4 1:34
5 0:05
6 0
推荐阅读
- javascript - useRef:渲染后状态变为未定义
- python - 并行化执行按位操作的代码
- angular - 如何从服务器渲染角度模板
- sql - 分区时的情况 - 组的同一列中具有两个特定值的组的返回值
- reactjs - 为什么用 ReactDOM.render 渲染的组件会丢失 react-redux 上下文(提供者)
- python - 如何加快 PlotDataItem.setData()?和/或仅在实时绘制流数据时重绘新点?
- c# - 如何在具有多个表的linq中使用join并使用orderby?
- vba - 根据文本框值填充多列列表框
- c - 实现可变参数使用函数的可选参数?
- amazon-web-services - 在 terraform 中使用本地变量进行变量的棘手转换