Skip to main content
 首页 » 编程设计

python之获取 Pandas 系列的最后一个完整序列

2025年05月04日19telwanggs

我有许多时间序列,其间隙存储为 pd.Series。我怎样才能有效地获得“最后一个完整的”数据点序列(即不包含任何 NaN 值)?

我原来的系列可能是这样的:

2014-12-01    500 
2015-02-01    700 
2015-03-01    700 
dtype: float64 

我可以使用 pd.Series.asfreq 轻松地将这个系列转换为常规系列,例如series.asfreq('MS') 给出:

2014-12-01    500 
2015-01-01    NaN 
2015-02-01    700 
2015-03-01    700 
dtype: float64 

在这种情况下,我想获得 2015-02-01 及以后的系列:

2015-02-01    700 
2015-03-01    700 
dtype: float64 

这是我想出的,但看起来很难看:

# Let i be the first position we're getting, default to entire series 
i = 0 
 
# Find any NaN values in the Series 
nan_index = series[series.isnull()].index 
if len(nan_index): 
    # Find the position of the last null value in the original 
    # series (+ 1 to skip it) 
    i = series.index.get_loc(nan_index[-1]) + 1 
 
series.iloc[i:] 

请您参考如下方法:

一个可能的技巧是寻找不为空的索引,以及空条目的累积和与空条目的总和匹配的位置。然后这可以通过花哨的索引来完成。

这只是 Dijkstra 可能会告诉我们所有人要避免的那种“聪明的把戏”,因为它的可读性不强并且可能会被巧妙地破坏(例如,这假设索引是按照您的期望提前排序的) .我认为更冗长但更直接的解决方案(例如直接计算最终 Null 的索引)没有任何问题,除非您可以分析它并确定这是一个主要的性能问题。

In [35]: s 
Out[35]:  
2014-12-01    500 
2015-02-01    700 
2015-03-01    700 
dtype: int64 
 
In [36]: s_ms = s.asfreq('MS') 
 
In [37]: s_ms_null = s_ms.isnull() 
 
In [38]: s[~s_ms_null & (s_ms_null.cumsum() == s_ms_null.sum())] 
Out[38]:  
2015-02-01    700 
2015-03-01    700 
dtype: int64