rio*_*oZg 4 python indexing time-series pandas
我有以下数据框。它是 OHLC 一分钟数据。显然我需要 T 列成为和索引才能使用时间序列功能
CHLOTV
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
Run Code Online (Sandbox Code Playgroud)
我用了:
df['T'] = pd.to_datetime(df['T'])
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好!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
Run Code Online (Sandbox Code Playgroud)
现在是有趣且无法解释的部分:
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
Run Code Online (Sandbox Code Playgroud)
看起来仍然不错,但是当我检查索引类型时,我得到:
RangeIndex(start=0, stop=13717, step=1)
Run Code Online (Sandbox Code Playgroud)
现在,如果我尝试:
df.index = pd.to_datetime(df.index)
Run Code Online (Sandbox Code Playgroud)
我最终得到:
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...
Run Code Online (Sandbox Code Playgroud)
这显然是错误的。
问题是: 1. 如果我将日期转换为索引,为什么我得不到正常的 DateTimeIndex?
谢谢!
如果输入数据是csv
最简单的使用参数parse_dates
和index_col
in read_csv
:
df = pd.read_csv(file, parse_dates=['T'], index_col=['T'])
Run Code Online (Sandbox Code Playgroud)
如果没有,则使用您的解决方案,不要忘记分配后出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)
Run Code Online (Sandbox Code Playgroud)
如果我将日期转换为索引,为什么我得不到正常的 DateTimeIndex?
因为您的索引是默认的 ( 0,1,2..
),所以df.index = pd.to_datetime(df.index)
解析integers
sns
并获得奇怪的日期时间。
归档时间: |
|
查看次数: |
9233 次 |
最近记录: |