ValueError:无法将字符串转换为float:'0:35:00'

时间:2019-10-15 08:02:16

标签: python numpy time-series normalization scaling

以下代码无法正常工作,我正在尝试转换CSV文件的“时间”列中的“时间序列数据”,其中仅包含我需要对其进行转换或规范化的一列:

# Normalize time series data
from pandas import read_csv
from sklearn.preprocessing import MinMaxScaler
# load the dataset and print the first 5 rows
series = read_csv("E:\Dataset\Copy3.csv", header=0)
print(series.head())
# prepare data for normalization
values = series.values
values = values.reshape((len(values), 1))
# train the normalization
scaler = MinMaxScaler(feature_range=(0, 1))
scaler = scaler.fit(values)
print('Min: %f, Max: %f' % (scaler.data_min_, scaler.data_max_))
# normalize the dataset and print the first 5 rows
normalized = scaler.transform(values)
for i in range(5):
 print(normalized[i])
# inverse transform and print the first 5 rows
inversed = scaler.inverse_transform(normalized)
for i in range(5):
 print(inversed[i])

Output:
         Time
     0  0:35:00
     1  0:55:00
     2  0:59:00
     3  2:11:00
     4  2:45:00

我收到此错误: Press here to show Error details         ValueError:无法将字符串转换为float:'0:35:00'

我希望得到一些帮助,谢谢大家

2 个答案:

答案 0 :(得分:0)

当您获得type列的pandas dtype时会发生什么?它是日期时间类型吗? 尝试series['Time']找出答案。

如果它返回类型对象,则需要在parse_dates=函数中使用read_csv参数。

您还可以尝试通过以下方式手动解析该列:

from datetime import datetime as dt
dt.strftime(series['time'], '%H:%M:%S')

它将把字符串转换成datetime对象供您使用。

答案 1 :(得分:0)

如果您要将一天中的时间转换为数字,因为一天中有86400秒,则可以将时间换算为(0,86399)。

from datetime import datetime
def intraday_time_scaler(t):
    tmp_time = datetime.strptime(t,'%H:%M:%S')
    return tmp_time.hour*3600 + tmp_time.minute*60 + tmp_time.second

df['time_scaled'] = df.apply(lambda row: intraday_time_scaler(row['Time']),axis=1)

或者,如果您的时间范围“ 00:00:00”超过了“ 23:59:59”,例如: '35:43:33',执行类似操作:

time_list = '35:43:33'.split(':')
time_numeric = int(time_list[0])*3600 + int(time_list[1])*60 + int(time_list[2])