【发布时间】:2018-06-23 05:07:07
【问题描述】:
我有以下数据框。它是 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?
- 如何将该 RangeIndex 转换为具有正确时间戳的 DateTimeIndex?
谢谢!
【问题讨论】:
-
您忘记只分配回
df = df.set_index('T')或使用df.set_index('T', inplace=True) -
但是如果使用
csv作为输入数据,最简单的就是df = pd.read_csv(file, parse_dates=['T'], index_col=['T']) -
输入数据为json。但我发现 df.index = df['T'] 可以解决问题
-
好的,然后使用第二个解决方案;)
-
我现在明白我的错误了。如果没有 df = df.set_index,我只是将整数转换为时间戳,将毫秒或纳秒添加到初始 Unix 时间戳。
标签: python pandas indexing time-series