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

无需循环实现Numpy三维数组各像素时间序列指定位置插入值

解决方案

现有两种完全不用循环的向量化实现方案,性能远高于嵌套循环,同时可以规避你原有代码的维度初始化错误:

方案1:直接使用np.insert向量化接口

np.insert原生支持沿指定轴插入和剩余维度匹配的高维数组,无需逐像素循环操作:

import numpy as np
arr_new = np.insert(arr_old, 15, arr_old[15], axis=0)

方案2:手动切片拼接(性能更优)

如果追求极致运行效率,可以直接通过数组拼接实现,避免np.insert内部的额外校验开销:
原理是将原数组前16个时间步(索引0~15)和从索引15开始的所有时间步拼接,刚好会在索引15位置重复一次原有值:

arr_new = np.concatenate([arr_old[:16], arr_old[15:]], axis=0)

正确性验证

你可以通过以下代码验证结果符合预期:

# 验证维度正确
print(arr_new.shape)  # 输出:(366, 180, 360)
# 验证插入位置数值正确
print(np.all(arr_new[15] == arr_old[15]))  # 输出:True
print(np.all(arr_new[16] == arr_old[15]))  # 输出:True
# 验证插入位置之后的数值无变化
print(np.all(arr_new[17:] == arr_old[16:]))  # 输出:True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:54:05