Skip to main content
 首页 » 编程设计

python之Pandas :如何将时间序列与互补日期合并

2024年11月01日10linjiqin

我想创建一个新的系列,其中包含(这一天的最低价)/(前一天收盘价)的最低价。所以首先我过滤每个条件的天数:

a=low['SPY'][low['SPY']<close['SPY'].shift(1)] 
b=close['SPY'].shift(1)[low['SPY']>=close['SPY'].shift(1)] 

现在a和b都有“洞”:

a: 
2013-06-21 16:00:00    1577.70 
2013-06-24 16:00:00    1560.33 
2013-06-28 16:00:00    1601.06 
2013-07-02 16:00:00    1606.77 
 
b: 
2013-06-25 16:00:00    1573.09 
2013-06-26 16:00:00    1588.03 
2013-06-27 16:00:00    1603.26 
2013-07-01 16:00:00    1606.28 

如何连接 a 和 b 以便我返回一个具有正确索引的时间序列?

我尝试了所有变体中的 pd.concat(或使用原始索引创建系列 C 并在其上合并),但它总是只是附加而不是按预期合并。

非常感谢!

请您参考如下方法:

为什么不在执行追加/连接之后才 sort_index?

In [11]: a.append(b) #  equivalent to pd.concat([a, b]) 
Out[11]: 
2013-06-21 16:00:00    1577.70 
2013-06-24 16:00:00    1560.33 
2013-06-28 16:00:00    1601.06 
2013-07-02 16:00:00    1606.77 
2013-06-25 16:00:00    1573.09 
2013-06-26 16:00:00    1588.03 
2013-06-27 16:00:00    1603.26 
2013-07-01 16:00:00    1606.28 
dtype: float64 
 
In [12]: a.append(b).sort_index() 
Out[12]: 
2013-06-21 16:00:00    1577.70 
2013-06-24 16:00:00    1560.33 
2013-06-25 16:00:00    1573.09 
2013-06-26 16:00:00    1588.03 
2013-06-27 16:00:00    1603.26 
2013-06-28 16:00:00    1601.06 
2013-07-01 16:00:00    1606.28 
2013-07-02 16:00:00    1606.77 
dtype: float64 

为了提高效率,pandas 默认不排序,需要明确询问。