如何获取numpy数组的所有可能的数组属性? Python:获取nd数组的所有可能的数组属性。使用itertools.product? 如果是,怎么做 在Python中,我有两个n维numpy数组A和B(B是零数组) 这是一个例子。您可以使用*运算符从列表中解包变量数,并将其交给itertools.product():
输出:如何获取numpy数组的所有可能的数组属性? Python:获取nd数组的所有可能的数组属性。使用itertools.product? 如果是,怎么做 在Python中,我有两个n维numpy数组A和B(B是零数组) 这是一个例子。您可以使用*运算符从列表中解包变量数,并将其交给itertools.product():,python,arrays,numpy,Python,Arrays,Numpy,输出: [[0 0 0] [0 0 1] [0 0 2] [0 0 3] [0 1 0] [0 1 1] [0 1 2] [0 1 3] [0 2 0] [0 2 1] [0 2 2] [0 2 3]] itertools产品应该可以工作 import numpy as np from itertools import product A = np.ones((2,3)) B = np.zeros((3,4)) r_rng = range(B.shape[0]-A.s
[[0 0 0]
[0 0 1]
[0 0 2]
[0 0 3]
[0 1 0]
[0 1 1]
[0 1 2]
[0 1 3]
[0 2 0]
[0 2 1]
[0 2 2]
[0 2 3]]
itertools产品应该可以工作
import numpy as np
from itertools import product
A = np.ones((2,3))
B = np.zeros((3,4))
r_rng = range(B.shape[0]-A.shape[0]+1)
c_rng = range(B.shape[1]-A.shape[1]+1)
for i,j in product(r_rng, c_rng):
C = B.copy()
C[i:i+A.shape[0],j:j+A.shape[1]]=A
print(C,'\n')
输出:
[[1. 1. 1. 0.]
[1. 1. 1. 0.]
[0. 0. 0. 0.]]
[[0. 1. 1. 1.]
[0. 1. 1. 1.]
[0. 0. 0. 0.]]
[[0. 0. 0. 0.]
[1. 1. 1. 0.]
[1. 1. 1. 0.]]
[[0. 0. 0. 0.]
[0. 1. 1. 1.]
[0. 1. 1. 1.]]
我将发布我获得的解决方案:
import numpy as np
from itertools import product
A=np.ones((2,3,2))
B=np.zeros((3,4,4))
coords=[]
for i in range(len(B.shape)):
delta = B.shape[i]-A.shape[i]+1
coords.append(list(range(delta)))
print(coords)
for start_idx in product(*coords):
idx=tuple(slice(start_idx[i], start_idx[i]+A.shape[i]) for i in range(len(A.shape)))
m=np.zeros(B.shape)
m.__setitem__(tuple(idx), A)
print(m)
ps:索引nd数组非常棘手“但是,我不知道如何将参数值传递给泛型
n
”是否有帮助?此示例适用于2D数组,在nd中,我们必须使用n'范围(B.shape[I]-a.shape[I]+1)表达式作为乘积函数的参数。那就是我不知道该怎么做。。。
[[1. 1. 1. 0.]
[1. 1. 1. 0.]
[0. 0. 0. 0.]]
[[0. 1. 1. 1.]
[0. 1. 1. 1.]
[0. 0. 0. 0.]]
[[0. 0. 0. 0.]
[1. 1. 1. 0.]
[1. 1. 1. 0.]]
[[0. 0. 0. 0.]
[0. 1. 1. 1.]
[0. 1. 1. 1.]]
import numpy as np
from itertools import product
A=np.ones((2,3,2))
B=np.zeros((3,4,4))
coords=[]
for i in range(len(B.shape)):
delta = B.shape[i]-A.shape[i]+1
coords.append(list(range(delta)))
print(coords)
for start_idx in product(*coords):
idx=tuple(slice(start_idx[i], start_idx[i]+A.shape[i]) for i in range(len(A.shape)))
m=np.zeros(B.shape)
m.__setitem__(tuple(idx), A)
print(m)