在1D数组中以不规则的间隔分配序列-Python/NumPy [英] Assign a sequence at irregular intervals in 1D array - Python / NumPy

查看:107
本文介绍了在1D数组中以不规则的间隔分配序列-Python/NumPy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数字序列,希望以不规则的间隔插入到更大的数组中:

I have a sequence of numbers that I would like to insert into a larger array at irregular intervals:

dates = np.zeros(15)
pattern = np.arange(3) + 1
starts = [2, 6, 11]
for start in starts:
    dates[start:start + pattern.size] = pattern

> [0 0 1 2 3 0 1 2 3 0 0 1 2 3 0]

我必须在大型(10K +)阵列上执行多次(100M +)次,所以我正在寻找一种通过广播或另一种有效方法来执行此操作的方法,以避免for循环.如果有帮助,模式将始终是一个范围.

I have to do this many (100M+) times on large (10K+) arrays, so I'm looking for a way to do this with broadcasting or another efficient method, avoiding a for loop. pattern will always be a range if that helps.

推荐答案

构造一个2D选择器数组以选择要用numpy.add.outer修改的dates的索引,然后对pattern进行广播分配选定的索引:

Construct a 2D selector array to select the indices of dates you want to modify with numpy.add.outer, then perform a broadcasted assignment of pattern into the selected indices:

dates[numpy.add.outer(starts, numpy.arange(len(pattern)))] = pattern

这篇关于在1D数组中以不规则的间隔分配序列-Python/NumPy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆