2017-07-27 122 views
1

假設我有熊貓以下數據框:通過在Pandas的另一列中添加新值來擴展Timeindex。

index = pd.date_range(start=pd.Timestamp('2017-07-01'), end=pd.Timestamp('2017-07-01') + pd.Timedelta('10D')) 
df = pd.DataFrame(data=np.random.rand(11), index=index , columns=['rand']) 
df.head() 

       rand 
2017-07-01 0.794164 
2017-07-02 0.948194 
2017-07-03 0.432187 
2017-07-04 0.750968 
2017-07-05 0.591830 

我想直到2017-07-19的附加價值,即數量擴展索引列十個新值添加到rand列。我想知道是否有任何方法可以通過將值添加到rand列來自動擴展時間索引。

+1

創建新的數據幀,然後調用'pd.concat' –

回答

1

可以創建新DataFrame然後concatappend

a = pd.date_range(df.index[-1] + pd.offsets.DateOffset(1), '2017-07-19') 
df1 = pd.DataFrame(data=np.random.rand(8), index=a , columns=['rand']) 

df = pd.concat([df, df1]) 
#alternative solution 
#df = df.append(df1) 
print (df) 
       rand 
2017-07-01 0.989012 
2017-07-02 0.549545 
2017-07-03 0.281447 
2017-07-04 0.077290 
2017-07-05 0.444469 
2017-07-06 0.472808 
2017-07-07 0.048522 
2017-07-08 0.163324 
2017-07-09 0.115951 
2017-07-10 0.627392 
2017-07-11 0.856182 
2017-07-12 0.650102 
2017-07-13 0.990722 
2017-07-14 0.470351 
2017-07-15 0.618294 
2017-07-16 0.282667 
2017-07-17 0.976003 
2017-07-18 0.673068 
2017-07-19 0.440531 
1

可以首先創建數據幀,然後通過設置時段的數據幀和頻率1D的長度設定的索引。如果要添加新的「蘭特」的數據,你可以使用pd.concat然後設置索引即

df = pd.DataFrame(data=np.random.rand(25), columns=['rand']) 
index = pd.date_range(start=pd.Timestamp('2017-07-01'),freq='1D',periods=df.shape[0]) 
df.set_index(index) 

輸出:

 
       rand 
2017-07-01 0.128300 
2017-07-02 0.039629 
2017-07-03 0.797066 
2017-07-04 0.023662 
2017-07-05 0.350117 
2017-07-06 0.945745 
2017-07-07 0.182427 
2017-07-08 0.792960 
2017-07-09 0.066210 
2017-07-10 0.774758 
2017-07-11 0.824564 
2017-07-12 0.872008 
2017-07-13 0.996188 
2017-07-14 0.671798 
2017-07-15 0.204903 
2017-07-16 0.087394 
2017-07-17 0.718709 
2017-07-18 0.224255 
2017-07-19 0.576668 
2017-07-20 0.789603 
2017-07-21 0.352212 
2017-07-22 0.6
2017-07-23 0.984145 
2017-07-24 0.182860 
2017-07-25 0.796244 
相關問題