【发布时间】:2015-07-30 12:35:35
【问题描述】:
我正在尝试找到一种方法来矢量化一个操作,其中我采用 1 个 numpy 数组并将每个元素扩展为 4 个新点。我目前正在使用 Python 循环进行操作。首先让我解释一下算法。
input_array = numpy.array([1, 2, 3, 4])
我想将此数组中的每个元素“扩展”或“扩展”到 4 个点。因此,元素零(值 1)将扩展为这 4 个点:
[0, 1, 1, 0]
这会发生在每个元素的最终数组中:
[0, 1, 1, 0, 0, 2, 2, 0, 0, 3, 3, 0, 0, 4, 4, 0]
我想让代码稍微通用,以便我也可以以不同的方式执行此“扩展”。例如:
input_array = numpy.array([1, 2, 3, 4])
这一次,每个点都通过向每个点添加 += .2 来扩展。所以,最终的数组是:
[.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]
我目前使用的代码如下所示。这是一种非常幼稚的方法,但似乎有一种方法可以加快大型数组的速度:
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])
【问题讨论】:
标签: python arrays numpy vectorization