我有许多时间序列,其中间隔存储为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:]
一个可能的技巧是寻找不为null的索引,以及null条目的总和与null条目的总和相匹配的索引。然后这可以用花哨的索引来完成。你知道吗
这正是Dijkstra可能会告诉我们大家要避免的那种“聪明的把戏”,因为它不那么可读,而且可能会被微妙地破坏(例如,这假设索引是按照您希望的提前排序的)。我认为更详细但更直接的解决方案(如直接计算最终空值的索引)没有任何问题,除非您能够分析它并确定这是一个主要的性能问题。你知道吗
相关问题 更多 >
编程相关推荐