Reputation: 1070
Assume that I have the following dataframe in Pandas:
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
I want to add ten new values to rand
column by extending index column by the number of added values i.e. until 2017-07-19
. I wonder if there is any way that the time index can be extended automatically only by adding values to rand
column.
Upvotes: 2
Views: 1618
Reputation: 862406
You can create new DataFrame
and then concat
or append
:
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
Upvotes: 1
Reputation: 30605
You can first create the dataframe and then set the index by setting period to the length of the dataframe and frequency to 1D. If you want to add new 'rand' data, you can use pd.concat
then set the index i.e
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)
Output :
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.601235 2017-07-23 0.984145 2017-07-24 0.182860 2017-07-25 0.796244
Upvotes: 1