通过在Pandas的另一列中添加新值来扩展Timeindex。
问题描述:
假设我有熊猫以下数据框:通过在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
列来自动扩展时间索引。
答
可以创建新DataFrame
然后concat
或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
答
可以首先创建数据帧,然后通过设置时段的数据帧和频率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
创建新的数据帧,然后调用'pd.concat' –