2

假设我在 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

我想rand通过将索引列扩展为添加值的数量来向列添加十个新值,即直到2017-07-19。我想知道是否有任何方法可以仅通过向列添加值来自动扩展时间索引rand

4

2 回答 2

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
于 2017-07-27T13:47:42.623 回答
1

您可以先创建数据帧,然后通过将 period 设置为数据帧的长度并将频率设置为 1D 来设置索引。如果要添加新的“rand”数据,可以使用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)

输出 :

                兰特
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
于 2017-07-27T13:49:31.377 回答