迭代一个n维的numpy数组,其中包含未知数量的numpy数组作为其值

lymnna71  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(81)

我有一个如下形式的numpy数组

[[array([ 1.  ,  3.25,  5.5 ,  7.75, 10.  ]) 0 0]
 [0 array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.]) 0]
 [0 0 0]]

字符串
数组是N维的,在特定的位置,我会有需要迭代的数组。我不知道最后的维度,也不知道有多少个数组。
我如何编写一个程序/函数,使我得到所有可能的N维Tensor/矩阵,每个位置只有一个值?(即,在有数组的位置,我需要迭代它们,我需要生成一个Tensor/矩阵列表,每个位置只有单个值。
我不知道这是否重要,但每个方向的最大长度是3。
(问题的物理意义:基本上,我想为另一个软件创建输入文件。我需要在我指定的方向上迭代电场的变化。因此,在一维中,我将只有X,Y和Z,对于二维,我将有XX,YY,ZZ,XZ等。在每一个位置,我都指出了我想要迭代的值的数组,即。例如linspace(10,100,10)等)。
先谢了。
我甚至不知道如何处理它,或者如何谷歌它。我在想,也许可以创建一些额外的函数来帮助我以某种方式迭代等。
因此,期望的结果是,在每次迭代之后,我都会得到一个numpy数组,其中只有数组中的值,因此我可以将其提交给另一个函数。例如,从上面的np.array得到的np. array将是

First,

[[1 0 0]
 [0 1 0]
 [0 0 0]]
Second, 

[[1 0 0]
 [0 2 0]
 [0 0 0]]

...

Last, 

[10 0 0]
 [0 10 0]
 [0 0 0]]

kqlmhetl

kqlmhetl1#

内置的itertools模块具有完美的功能:产物
然后就只需要处理numpy数组了。我发现其中的关键是创建一个布尔值掩码,指示嵌套数组的位置。
我只在3x3矩阵上测试过,但我认为它应该适用于任何数组。

from itertools import product

import numpy as np

array = np.array([[np.array([1, 2]), 0.5, 0.75],
                  [-0.5, np.array([10, 20]), -0.75],
                  [np.array([-1, -2]), 3.5, 3.75]], dtype=object)

# create a vectorized function to find nested arrays
is_cell_an_array = np.vectorize(lambda cell: isinstance(cell, np.ndarray))
# create an array of booleans indicating where the nested cells are
nested_mask = is_cell_an_array(array)

# use itertools.product to generate all the combinations of the nested arrays
for permutation in product(*array[nested_mask]):
    # create a new array
    new_array = np.zeros(array.shape, dtype=float)
    # copy in the unique combination of the nested arrays for this loop
    new_array[nested_mask] = permutation
    # copy in the rest of the values from the original array
    new_array[~nested_mask] = array[~nested_mask]

    print(new_array)

字符串

相关问题