问题描述
我试图找到一种向量化操作的方法,其中我采用1个numpy数组并将每个元素扩展为4个新点.我目前正在使用Python循环进行此操作.首先让我解释一下算法.
I'm trying to find a way to vectorize an operation where I take 1 numpy array and expand each element into 4 new points. I'm currently doing it with Python loop. First let me explain the algorithm.
input_array = numpy.array([1, 2, 3, 4])
我想将该数组中的每个元素扩展"或扩展"到4个点.因此,元素零(值1)将扩展为这4个点:
I want to 'expand' or 'extend' each element in this array to 4 points. So, element zero (value 1) would be expanded to these 4 points:
[0, 1, 1, 0]
对于每个元素,最终都会得到以下最终数组:
This would happen for each element to end up with a final array of:
[0, 1, 1, 0, 0, 2, 2, 0, 0, 3, 3, 0, 0, 4, 4, 0]
我想使代码稍微通用一些,以便我也可以以其他方式执行此扩展".例如:
I'd like to make the code slightly generic so that I could also perform this 'expansion' in a different way. For example:
input_array = numpy.array([1, 2, 3, 4])
这次,通过在每个点上添加+ = 0.2来扩展每个点.因此,最终的数组将是:
This time each point is expanded by adding += .2 to each point. So, the final array would be:
[.8, .8, 1.2, 1.2, 1.8, 1.8, 2.2, 2.2, 2.8, 2.8, 3.2, 3.2, 3.8, 3.8, 4.2, 4.2]
我当前正在使用的代码如下所示.这是一种非常幼稚的方法,但是似乎有一种方法可以加快大型阵列的速度:
The code I'm currently using looks like this. It's a pretty naive approach that works but seems like there would be a way to speed it up for large arrays:
output = []
for x in input_array:
output.append(expandPoint(x))
output = numpy.concatenate(output)
def expandPoint(x):
return numpy.array([0, x, x, 0])
def expandPointAlternativeStyle(x):
return numpy.array([x - .2, x - .2, x + .2, x + .2])
推荐答案
似乎您想在input_array
与包含扩展元素的数组之间进行逐元素运算.对于这些,您可以使用 broadcasting
.
It seems you want to want to do elementwise operations between input_array
and the array that contains the extending elements. For these, you can use broadcasting
.
对于第一个示例,似乎您正在执行elementwise multiplication
-
For the first example, it seems you are performing elementwise multiplication
-
In [424]: input_array = np.array([1, 2, 3, 4])
...: extend_array = np.array([0, 1, 1, 0])
...:
In [425]: (input_array[:,None] * extend_array).ravel()
Out[425]: array([0, 1, 1, 0, 0, 2, 2, 0, 0, 3, 3, 0, 0, 4, 4, 0])
对于第二个示例,似乎您正在执行elementwise addition
-
For the second example, it seems you are performing elementwise addition
-
In [422]: input_array = np.array([1, 2, 3, 4])
...: extend_array = np.array([-0.2, -0.2, 0.2, 0.2])
...:
In [423]: (input_array[:,None] + extend_array).ravel()
Out[423]:
array([ 0.8, 0.8, 1.2, 1.2, 1.8, 1.8, 2.2, 2.2, 2.8, 2.8, 3.2,
3.2, 3.8, 3.8, 4.2, 4.2])
这篇关于向量化numpy数组扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!