2014-12-20 98 views
1

我想爲時間序列中的時間賦值,該時間序列當前不存在於索引中,並將其插入到正確的位置。即2014年1月2日爲以下幾點:python熊貓時間序列:賦值給時間(當前從索引中省略)

import pandas as pd 
from numpy.random import randn as randn 
rng = pd.date_range('1/3/2014', periods=6, freq='D') 
ts = pd.Series(randn(len(rng)), index=rng) 
ts 
Out[23]: 
2014-01-03 1.876969 
2014-01-04 -0.460700 
2014-01-05 0.587874 
2014-01-06 0.205369 
2014-01-07 -1.319009 
2014-01-08 0.907479 
Freq: D, dtype: float64 

分配後,TS應該是:

2014-01-02 1 # or whatever 
2014-01-03 1.876969 
... 
2014-01-08 0.907479 
Freq: D, dtype: float64 

(或更一般的基於時間/日期的正確位置。)這是什麼我已經試過:

ts['2014-01-02'] = 1 # All append date and value to end 
ts[pd.to_datetime('2014-01-02')] = 1 
ts[pd.datetime(2014, 1, 2)] = 1 

temp = pd.Series([1], index=['2014-01-02']) 
ts.append(temp) # No effect 
ts.replace(temp) # Error 
ts.update(temp) # No effect 

我認爲必須有一種方法做這樣的東西看似簡單,但它的確沒有跳出我......

回答

1

有時您可能不希望對索引進行排序。所以熊貓不會自動做到這一點。如果要排序的指標,叫sort_index

ts['2014-01-02'] = 1 
ts = ts.sort_index() 

產生

In [75]: ts 
Out[75]: 
2014-01-02 1.000000 
2014-01-03 -0.664830 
2014-01-04 0.654928 
2014-01-05 0.704723 
2014-01-06 0.646540 
2014-01-07 0.364220 
2014-01-08 -1.346799 
dtype: float64 
+0

謝謝!如果我獲得足夠的聲譽,我會贊成這一點:) – birone

相關問題