簡體   English   中英

Pandas - 如何將RangeIndex轉換為DateTimeIndex

[英]Pandas - how to convert RangeIndex into DateTimeIndex

我有以下數據幀。 它是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 

我用了:

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?

謝謝!

如果輸入的數據csv的simpliest是使用參數parse_datesindex_colread_csv

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

如果沒有,那么使用你的解決方案,不要忘記分配set_index輸出,如果需要在DatetimeIndex使用T而不是df['T']后丟棄列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)解析integersns一樣,得到奇怪的日期時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM