Pandas - 如何将RangeIndex转换为DateTimeIndex

时间:2018-01-14 09:29:00

标签: python pandas indexing time-series

我有以下数据框。它是OHLC一分钟数据。显然我需要T列成为和索引才能使用时间序列函数

C H L O T V

13712 6873.0 6873.0 6873.0 6873.0 2018-01-13T17:17:00 799.448421 
13713 6878.0 6878.0 6875.0 6875.0 2018-01-13T17:18:00 1707.578666 
13714 6880.0 6880.0 6825.0 6825.0 2018-01-13T17:21:00 481.245707 
13715 6876.0 6876.0 6876.0 6876.0 2018-01-13T17:22:00 839.177283 
13716 6870.0 6878.0 6830.0 6878.0 2018-01-13T17:23:00 4336.830277 

我用过:

df['T'] = pd.to_datetime(df['T'])

到目前为止一切顺利! T列现在被识别为日期

检查:

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 13717 entries, 1970-01-01 00:00:00 to 1970-01-01 00:00:00.000013716
Data columns (total 7 columns):
BV    13717 non-null float64
C     13717 non-null float64
H     13717 non-null float64
L     13717 non-null float64
O     13717 non-null float64
T     13717 non-null datetime64[ns]
V     13717 non-null float64
dtypes: datetime64[ns](1), float64(6)
memory usage: 857.3 KB

现在出现了有趣且无法解释的部分:

df.set_index(df['T'])


   C H L O T V
T

2018-01-03 17:27:00 5710.0 5710.0 5663.0 5667.0 2018-01-03 17:27:00 3863.030204 
2018-01-03 17:28:00 5704.0 5710.0 5663.0 5710.0 2018-01-03 17:28:00 1208.627542 
2018-01-03 17:29:00 5699.0 5699.0 5663.0 5663.0 2018-01-03 17:29:00 1755.123688 

看起来还不错,但是当我检查索引的类型时我得到了:

RangeIndex(start=0, stop=13717, step=1)

现在如果我尝试:

df.index = pd.to_datetime(df.index)

我最终得到了:

DatetimeIndex([          '1970-01-01 00:00:00',
               '1970-01-01 00:00:00.000000001',
               '1970-01-01 00:00:00.000000002',
               '1970-01-01 00:00:00.000000003',
               '1970-01-01 00:00:00.000000004' and so on...

这显然是错误的。

问题是: 1.如果我将日期转换为索引,为什么不能获得正常的DateTimeIndex?

  1. 如何将RangeIndex转换为具有正确时间戳的DateTimeIndex?
  2. 谢谢!

1 个答案:

答案 0 :(得分:3)

如果输入数据为csv,则最简单的方法是在read_csv中使用参数parse_datesindex_col

df = pd.read_csv(file, parse_dates=['T'], index_col=['T'])

如果没有,那么请使用您的解决方案,不要忘记分配set_index的输出,如果需要在T使用DatetimeIndex之后删除列T df['T']

df['T'] = pd.to_datetime('T')
df = df.set_index('T')

#alternative solution
#df.set_index('T', inplace=True)
  

如果我将日期转换为索引,为什么不能获得正常的DateTimeIndex?

因为您的索引是默认的(0,1,2..),所以df.index = pd.to_datetime(df.index)解析integers就像ns一样,并获得奇怪的日期时间。

相关问题