Python 如何使用范围(x,y)中的每列值创建NxM矩阵?
问题: 我想创建一个5维numpy矩阵,每个列的值限制在一个范围内。我在网上找不到解决这个问题的办法 我试图在表单中生成一个规则列表Python 如何使用范围(x,y)中的每列值创建NxM矩阵?,python,numpy,Python,Numpy,问题: 我想创建一个5维numpy矩阵,每个列的值限制在一个范围内。我在网上找不到解决这个问题的办法 我试图在表单中生成一个规则列表 Rule: (wordIndex, row, col, dh, dv) 每列的值的范围为((0-7),(0,11),(0,11),(-1,1),(-1,1))。我想生成所有可能的组合 我可以很容易地使用五个循环来制作矩阵,一个循环在另一个循环中 m, n = 12, 12 rules =[] for wordIndex in range(0, 15):
Rule: (wordIndex, row, col, dh, dv)
每列的值的范围为((0-7),(0,11),(0,11),(-1,1),(-1,1))。我想生成所有可能的组合
我可以很容易地使用五个循环来制作矩阵,一个循环在另一个循环中
m, n = 12, 12
rules =[]
for wordIndex in range(0, 15):
for row in range(0,m):
for col in range(0,n):
for dh in range(-1,2):
for dv in range(-1,2):
rules.append([wordIndex, row, col, dh, dv])
但是这种方法需要大量的时间才能完成,我想知道是否有更好的、矢量化的方法来使用numpy解决这个问题
我尝试了以下方法,但没有一种有效:
rules = np.mgrid[words[0]:words[-1], 0:11, 0:11, -1:1, -1:1]
rules = np.rollaxis(words,0,4)
rules = rules.reshape((len(words)*11*11*3*3, 5))
另一种失败的方法是:
values = list(itertools.product(len(wordsGiven()), range(11), range(11), range(-1,1), range(-1,1)))
我也尝试了np.arange(),但似乎不知道如何将if用于多维数组。我认为应该有更好的方法。但为了以防万一,如果你找不到它,这里有一种基于数组的方法:
shape = (8-0, 12-0, 12-0, 2-(-1), 2-(-1))
a = np.zeros(shape)
#create array of indices
a = np.argwhere(a==0).reshape(*shape, len(shape))
#correct the ranges that does not start from 0, here 4th and 5th elements (dh and dv) reduced by -1 (starting range).
#You can adjust this for any other ranges and elements easily.
a[:,:,:,:,:,3:5] -= 1
a的前几个要素:
[[[[[[ 0 0 0 -1 -1]
[ 0 0 0 -1 0]
[ 0 0 0 -1 1]]
[[ 0 0 0 0 -1]
[ 0 0 0 0 0]
[ 0 0 0 0 1]]
[[ 0 0 0 1 -1]
[ 0 0 0 1 0]
[ 0 0 0 1 1]]]
[[[ 0 0 1 -1 -1]
[ 0 0 1 -1 0]
[ 0 0 1 -1 1]]
[[ 0 0 1 0 -1]
[ 0 0 1 0 0]
[ 0 0 1 0 1]]
[[ 0 0 1 1 -1]
[ 0 0 1 1 0]
[ 0 0 1 1 1]]]
[[[ 0 0 2 -1 -1]
[ 0 0 2 -1 0]
[ 0 0 2 -1 1]]
[[ 0 0 2 0 -1]
[ 0 0 2 0 0]
[ 0 0 2 0 1]]
[[ 0 0 2 1 -1]
[ 0 0 2 1 0]
[ 0 0 2 1 1]]]
...