利用numpy和pandas处理csv文件中的时间2

来源:互联网 发布:新兴重工查知的老婆 编辑:程序博客网 时间:2024/05/22 12:58

在机器学习和深度学习的过程中,对于处理预测,回归问题,有时候变量是时间,需要进行合适的转换处理后才能进行学习分析,关于时间的变量如下所示,利用pandas和numpy对csv文件中时间进行处理。
上一篇博客中datetime.datetime.toordinal()将日期转为数字,例如2017-12-12—》XXXXXX
利用time模块的time.mktime可以将时间转为数字例如2017-12-12 06:45:23 —》XXXXXX

#coding:utf-8import timeimport pandas as pdimport numpy as npimport pickle#用pandas将时间转为标准格式dateparse = lambda dates: pd.datetime.strptime(dates,'%d/%m/%Y %H:%M:%S')#将时间栏合并,并转为标准时间格式rawdata = pd.read_csv('RealMarketPriceDataPT.csv',parse_dates={'timeline':['date','(UTC)']},date_parser=dateparse)"""#定义一个将日期转为数字的函数,s为字符串def datestr2num(s):    #toordinal()将日期格式字符串转为数字    return datetime.datetime.strptime(s,'%Y-%m-%d %H:%M:%S').toordinal()"""#定义一个函数将时间转为数字def daystr2num(s):    x_convert = time.strptime(s,'%Y-%m-%d %H:%M:%S')    return int(time.mktime(x_convert))#x_convert = time.strptime(str(rawdata.ix[i,0]),'%Y-%m-%d %H:%M:%S')#x_convert = int(time.mktime(x_convert))x = []y = []new_date = []for i in range(rawdata.shape[0]):    x_convert = daystr2num(str(rawdata.ix[i,0]))    #new_date存储int类型的时间戳    new_date.append(x_convert)    y_convert = rawdata.ix[i,1].astype(np.float32)    x.append(x_convert)    y.append(y_convert)x = np.array(x).astype(np.float32)/1000000000#x = np.diff(x)#y = np.diff(y)#预测的datapred_value = []new_pred_date = []pred = ['2017-01-01 00:00:00','2017-02-01 10:00:00','2017-03-05 05:00:00','2017-04-18 21:00:00','2017-05-22 04:00:00',       '2017-06-15 05:00:00','2017-07-03 19:00:00','2017-08-08 13:00:00','2017-09-29 23:00:00','2017-10-01 09:00:00']for i in range(len(pred)):    pred_convert = daystr2num(pred[i])    #new_pred_date存储int类型的时间戳    new_pred_date.append(pred_convert)    pred_value.append(pred_convert)pred_value = np.array(pred_value).astype(np.float32)/1000000000with open('price.pickle','wb') as f:    pickle.dump((x,y,pred_value,pred),f)#定义一个函数将时间戳转为时间def strtotime(int_a):    timearray = time.localtime(int_a)    return time.strftime('%Y-%m-%d %H:%M:%S',timearray)#timearray = time.localtime(new_date[0])#otherstyletime = time.strftime('%Y-%m-%d %H:%M:%S',timearray)#print(x[0:50])#print(y[0:50])#print(pred_value[0:10])#print(strtotime(new_date[0]),'------>>>>>>',new_date[0])#print(strtotime(new_date[10]),'------>>>>>>',new_date[10])#print(strtotime(new_date[20]),'------>>>>>>',new_date[20])#print(strtotime(new_date[30]),'------>>>>>>',new_date[30])#print(strtotime(new_date[40]),'------>>>>>>',new_date[40])#print(strtotime(new_date[50]),'------>>>>>>',new_date[50])

结果

这里写图片描述