2016-12-30 75 views
2

我的數據框看起來是這樣的:堆疊多指標數據幀和合並指數

     00:00 01:00 02:00 03:00 04:00 05:00 06:00 07:00 
Code Alias Date                 
RO FI 05.07.2010 53.97 52.11 52.11 52.11 52.11 52.11 51.85 51.55 
    JY 05.07.2010 53.97 52.11 52.11 52.11 52.11 52.11 51.85 65.85 
    SE 05.07.2010 53.97 52.11 52.11 52.11 52.11 52.11 51.85 51.55 
    SJ 05.07.2010 53.97 52.11 52.11 52.11 51.49 52.11 51.85 51.55 

使用df.stack(),我得到的列(小時)作爲一個單獨的索引。如何合併「日期」索引和新的「小時」索引以形成DateTime索引?

像這樣:

       Value 
Code Alias Date                 
RO FI 05.07.2010 00:00 53.97 
      05.07.2010 01:00 52.11 
      05.07.2010 02:00 52.11 

回答

1

這不是很漂亮,但它會做

  • 使用strftimeDate成一個字符串,並與Hour
  • 然後串聯傳遞到pd.to_datetime

s = df.rename_axis('Hour', 1).stack() 

d1 = s.reset_index(['Date', 'Hour'], name='Value') 

d1.set_index(
    pd.to_datetime(
     d1.Date.dt.strftime('%Y-%m-%d ') + 
     d1.Hour 
    ), append=True 
).Value 

Code Alias      
RO FI  2010-05-07 00:00:00 53.97 
      2010-05-07 01:00:00 52.11 
      2010-05-07 02:00:00 52.11 
      2010-05-07 03:00:00 52.11 
      2010-05-07 04:00:00 52.11 
      2010-05-07 05:00:00 52.11 
      2010-05-07 06:00:00 51.85 
      2010-05-07 07:00:00 51.55 
     JY  2010-05-07 00:00:00 53.97 
      2010-05-07 01:00:00 52.11 
      2010-05-07 02:00:00 52.11 
      2010-05-07 03:00:00 52.11 
      2010-05-07 04:00:00 52.11 
      2010-05-07 05:00:00 52.11 
      2010-05-07 06:00:00 51.85 
      2010-05-07 07:00:00 65.85 
     SE  2010-05-07 00:00:00 53.97 
      2010-05-07 01:00:00 52.11 
      2010-05-07 02:00:00 52.11 
      2010-05-07 03:00:00 52.11 
      2010-05-07 04:00:00 52.11 
      2010-05-07 05:00:00 52.11 
      2010-05-07 06:00:00 51.85 
      2010-05-07 07:00:00 51.55 
     SJ  2010-05-07 00:00:00 53.97 
      2010-05-07 01:00:00 52.11 
      2010-05-07 02:00:00 52.11 
      2010-05-07 03:00:00 52.11 
      2010-05-07 04:00:00 51.49 
      2010-05-07 05:00:00 52.11 
      2010-05-07 06:00:00 51.85 
      2010-05-07 07:00:00 51.55 
Name: Value, dtype: object 
+0

非常感謝!使用.dt.strftime由於某種原因產生了錯誤,但它使用pd.to_datetime(d1.Date +「」+ d1.Hour,dayfirst = True) – ArOLi