【发布时间】:2016-11-05 07:52:47
【问题描述】:
假设我有一个函数 f,它可以将坐标作为参数并返回一个整数(在本例中为 f(x))。坐标可以是多维的并且是列表的形式。我的目标是用两个坐标之间的所有值填充一个 numpy 数组。我试图列出所有可能的索引并将其用作矢量化函数的输入。
这是我的二维坐标代码:
import itertools
import numpy
def index_array(lower_corner, upper_corner):
x_range = range(lower_corner[0], upper_corner[0])
y_range = range(lower_corner[1], upper_corner[1])
return numpy.array(list(itertools.product(x_range, y_range)))
print(index_array([2, -2], [5, 3]))
这将返回预期的索引列表:
[[ 2 -2]
[ 2 -1]
[ 2 0]
[ 2 1]
[ 2 2]
[ 3 -2]
[ 3 -1]
[ 3 0]
[ 3 1]
[ 3 2]
[ 4 -2]
[ 4 -1]
[ 4 0]
[ 4 1]
[ 4 2]]
这是我对 n 维的尝试:
import itertools
import numpy
def f(x):
# dummy function
return x + 5
def index_array(lower_corner, upper_corner):
# returns all indices between two n-dimensional points
range_list = []
for n in range(len(lower_corner)):
range_list.append(range(lower_corner[n], upper_corner[n]))
return numpy.array(list(itertools.product(*range_list)))
lower_corner = numpy.array([2, -2])
upper_corner = numpy.array([5, 3])
indices = index_array(lower_corner, upper_corner)
vect_func = numpy.vectorize(f)
results = vect_func(indices)
print(results)
虽然这可行,但速度很慢并且需要大量内存。是否有可能以更有效的方式编写它?我可以考虑使用 numpy.meshgrid 但我不知道如何使用它。
【问题讨论】:
标签: python numpy multidimensional-array iterator coordinates