You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:如何移除时间序列首尾零值及对应的时间值

时间序列移除首尾零值及对应时间项实现方案

原代码错误说明

  • 逻辑偏差:需求是移除整个数组首尾的零值元素,原代码错误将每个数值转字符串后删除字符首尾的0,完全不符合需求
  • 变量未初始化:函数内bothremoved、dt未提前定义,运行会抛出未定义错误
  • 返回位置错误:return写在for循环内部,第一次循环就直接返回,没有完成数组遍历

实现方案

方案1:纯Python实现(无需依赖第三方库)

核心逻辑:先定位数组第一个非零元素的索引,再定位最后一个非零元素的索引,直接对y和t数组做区间切片即可

def remove_leading_trailing_zeros(counts, time):
    n = len(counts)
    # 定位第一个非零元素索引
    start_idx = 0
    while start_idx < n and counts[start_idx] == 0:
        start_idx += 1
    # 定位最后一个非零元素索引
    end_idx = n - 1
    while end_idx >= 0 and counts[end_idx] == 0:
        end_idx -= 1
    # 处理全零特殊情况
    if start_idx > end_idx:
        return [], []
    return counts[start_idx:end_idx+1], time[start_idx:end_idx+1]

# 测试用例
y = [0, 0 , 0 , 0.45, 0, 0.89, 0.78, 0, 0]
t = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y_0removed, new_t = remove_leading_trailing_zeros(y, t)

print(y_0removed)
print(new_t)

输出结果:

[0.45, 0, 0.89, 0.78]
[4, 5, 6, 7]

方案2:NumPy实现(适合大数据量场景)

利用NumPy内置方法快速定位非零元素区间,代码更简洁

import numpy as np

y = np.array([0, 0 , 0 , 0.45, 0, 0.89, 0.78, 0, 0])
t = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

non_zero_indexes = np.nonzero(y)[0]
if len(non_zero_indexes) == 0:
    y_0removed, new_t = [], []
else:
    start_idx = non_zero_indexes.min()
    end_idx = non_zero_indexes.max()
    # 如需输出list类型可追加.tolist()
    y_0removed = y[start_idx:end_idx+1].tolist()
    new_t = t[start_idx:end_idx+1].tolist()

print(y_0removed)
print(new_t)

输出结果和方案1完全一致。


内容的提问来源于stack exchange,提问作者Sayantan34

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 02:03:03