转化dataframe中一组序列为时间序列的方法

直接使用的代码已经被更改:

原来引用的代码:

hs300_hf.index = hs300_hf.index.to_datetime() 
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-30-092b68ed77cc> in <module>
----> 1 hs300_hf.index = hs300_hf.index.to_datetime()

AttributeError: 'Index' object has no attribute 'to_datetime'     

会报错,现在面对要把’object’类型的数据转化为’datetime’类型,方法有二:

一、to_datetime()的最新用法;

hs300_hf['date'] = pd.to_datetime(hs300_hf['date'])
hs300_hf.set_index('date',inplace=True)
hs300_hf.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 513 entries, 2019-05-23 14:55:00 to 2019-06-10 13:34:00
Data columns (total 8 columns):
open             513 non-null float64
close            513 non-null float64
high             513 non-null float64
low              513 non-null float64
volume           513 non-null float64
amount           513 non-null object
turnoverratio    513 non-null object
code             513 non-null object
dtypes: float64(5), object(3)
memory usage: 36.1+ KB

二、datetimeindex的用法

hs300_hf.set_index('date',inplace=True)
hs300_hf.index = pd.DatetimeIndex(hs300_hf.index)
hs300_hf.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 509 entries, 2019-05-23 14:55:00 to 2019-06-10 13:14:00
Data columns (total 8 columns):
open             509 non-null float64
close            509 non-null float64
high             509 non-null float64
low              509 non-null float64
volume           509 non-null float64
amount           509 non-null object
turnoverratio    509 non-null object
code             509 non-null object
dtypes: float64(5), object(3)
memory usage: 35.8+ KB

两种都是一样的结果。

你可能感兴趣的:(常用代码)