如何获取numpy数组的所有可能的数组属性?

3
  • Python: 如何获取n维数组的所有可能的数组属性?可以使用itertools.product吗?
    • 如果可以,应该如何使用?
  • 在Python中,我有两个n维numpy数组AB(其中B是一个零数组)。
  • 这样的方式A.shape[i] <= B.shape[i],对于任何i0n之间。 我想创建一个for循环,以便每次迭代将A分配给B的不同子集,在这种方式下,每个可能的位置都被占用,直到for循环结束。

例如,对于A = np.array([[1,1,1],[1,1,1]])B = np.zeros((3,4)),我会得到以下结果(每次迭代输出一个):

1 1 1 0       0 1 1 1       0 0 0 0      0 0 0 0
1 1 1 0       0 1 1 1       1 1 1 0      0 1 1 1
0 0 0 0       0 0 0 0       1 1 1 0      0 1 1 1

对于固定的n维度,这很简单,只需为每个维度使用嵌套的for循环。 然而,我想要一个通用的n维度。

我的方法是使用itertools.product获取所有索引的组合。在上面的示例中,product([0,1],[0,1])会遍历(0,0),(0,1),(1,0),(1,1),然后我就得到了我的索引。但是,我不知道如何向通用的n传递参数值给product函数。有什么建议吗?有更好的做法吗?


1
然而,我不知道如何将参数的值传递给泛型 n 的 product 函数。这个链接 https://dev59.com/HHVD5IYBdhLWcg3wQZUg 有帮助吗? - Karl Knechtel
3个回答

2

itertools product 应该可以正常运行。

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.]]

这个例子是针对一个二维数组的,在n维数组中,我们需要使用n个“range(B.shape[i]-A.shape[i]+1)”表达式作为product函数的参数。但我不知道该怎么做... - Jonathan alis

1
这里有一个例子。您可以使用 * 运算符从列表中解包变量数量的参数,并将其传递给 itertools.product()
import itertools

size1 = (3,5,6)
size2 = (2,2,2)
N = len(size1)
coords = []
for i in range(N):
    delta = size1[i]-size2[i]
    coords.append(list(range(delta)))
    
print(coords)
it = itertools.product(*coords)
arr = np.array(list(it))
print(arr)

Output:

[[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]]

0
我将发布我得到的解决方案:
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)

提示:对nd数组进行索引非常棘手


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接