例如,我有两个不相交的时间序列对象
-ts1
Date Price
2010-01-01 1800.0
2010-01-04 1500.0
2010-01-08 1600.0
2010-01-09 1400.0
Name: Price, dtype: float64
-ts2
Date Price
2010-01-02 2000.0
2010-01-03 2200.0
2010-01-05 2010.0
2010-01-07 2100.0
2010-01-10 2110.0
如何将两者合并为一个应按日期排序的单一时间序列?喜欢
-ts3
Date Price
2010-01-01 1800.0
2010-01-02 2000.0
2010-01-03 2200.0
2010-01-04 1500.0
2010-01-05 2010.0
2010-01-07 2100.0
2010-01-08 1600.0
2010-01-09 1400.0
2010-01-10 2110.0
最佳答案
使用 pandas.concat
或 DataFrame.append
连接在一起,然后使用DataFrame.sort_values
列添加 Date
,最后使用参数DataFrame.reset_index
设置默认索引 drop=True
:
df3 = pd.concat([df1, df2]).sort_values('Date').reset_index(drop=True)
选择:
df3 = df1.append(df2).sort_values('Date').reset_index(drop=True)
print (df3)
Date Price
0 2010-01-01 1800.0
1 2010-01-02 2000.0
2 2010-01-03 2200.0
3 2010-01-04 1500.0
4 2010-01-05 2010.0
5 2010-01-07 2100.0
6 2010-01-08 1600.0
7 2010-01-09 1400.0
8 2010-01-10 2110.0
编辑:
如果使用TimeSeries,则解决方案可以简化:
s3= pd.concat([s1, s2]).sort_index()