首页 > 解决方案 > 如何将包含“4:20”等字符串的列中的数据转换为浮点数

问题描述

在我的数据框中,有一列包含如下值:

 PowerPlayTimeOnIce
       0:05
       0:05
       1:24
       3:29
       1:34
        0
       0:05
        0
        0

如何将这些转换为浮点数?

此方法无效:

df["powerPlayTimeOnIce"] = df["powerPlayTimeOnIce"].astype('float')

编辑:更新数据示例以更好地适应问题

标签: pythonpython-3.xpandastype-conversion

解决方案


使用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

推荐阅读