python - 如何在numpy中指定迭代器的深度?

标签 python arrays numpy iterator

我在 numpy 中有一个多维数组(例如 4D),我想指定 numpy 迭代器的深度,但我不知道该怎么做?

例如,假设我有一个 4D numpy 数组,我想从迭代器中获取仅用于 2D 级别的元素(这样每个项目也是 2D 的)。有没有办法在迭代器中指定这样的深度?

我真的很想使用迭代器而不是双循环,我想使用 numpy 而不是其他工具,例如字典和 pandas。

因此,我希望此代码输出 [1 2] 而不是 1,2...

x = np.array(\
(\
\
(\
(np.array([1,2]), np.array([1,2])),\
(np.array([1,2]), np.array([1,2]))\
),\
\
(\
(np.array([1,2]), np.array([1,2])),\
(np.array([1,2]), np.array([1,2]))\
)\
\
)
, dtype = np.ndarray)

for i in np.nditer(x, flags = ["refs_ok"]):
     print i

给我:

1
2
1
2
1
2
1
2
1
2
1
2
1
2
1
2

代替:

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

最佳答案

np.ndindex 在迭代指定维度方面做得很好。

你的 x 是一个 4d object 数组 dtype=ndarray 变成了 dtype=object。尽管元组的大小都相同,但元素实际上只是标量,而不是数组。

In [385]: x
Out[385]: 
array([[[[1, 2],
         [1, 2]],

        [[1, 2],
         [1, 2]]],


       [[[1, 2],
         [1, 2]],

        [[1, 2],
         [1, 2]]]], dtype=object)

In [386]: x.shape
Out[386]: (2, 2, 2, 2)

在任何情况下,np.ndindex 都会生成将迭代给定形状数组的索引。

In [387]: for i,j in np.ndindex(x.shape[:2]):
    print(i,j)       
    print(x[i,j])
   .....:     
0 0
[[1 2]
 [1 2]]
0 1
[[1 2]
 [1 2]]
1 0
[[1 2]
 [1 2]]
1 1
[[1 2]
 [1 2]]

ndindex 的关键部分是 as_strided 用于生成大小合适的虚拟矩阵,以及 nditermulti_index 模式生成索引。

这种用法的早期示例:

https://stackoverflow.com/a/28727290/901925

Iterating over first d axes of numpy array

更多关于尝试创建数组数组(不仅仅是更高维的数字数组)的信息:

Convert a numpy array to an array of numpy arrays

要使 x 真正成为数组的数组,您需要执行以下操作:

In [397]: x=np.zeros((2,2,2),dtype=object)
In [398]: for ijk in np.ndindex(x.shape):
             x[ijk] = np.array([1,2])


In [399]: x
Out[399]: 
array([[[array([1, 2]), array([1, 2])],
        [array([1, 2]), array([1, 2])]],

       [[array([1, 2]), array([1, 2])],
        [array([1, 2]), array([1, 2])]]], dtype=object)

另一种选择是 reshape 初始尺寸,因此您可以对这些尺寸进行平面迭代:

for i in x.reshape(-1,2):
    print(i)

nditer(以及扩展名 ndindex)被描述为高效,但这更适用于它的 C/cython 使用。在纯 Python 代码中,迭代机制并不那么重要。迭代主体中的操作通常需要更多时间。当您需要对多个数组进行坐标迭代时,nditer 也是最佳选择,如 out[...] = a[...] * b[...]。仅迭代一个数组并没有什么特别之处。

http://docs.scipy.org/doc/numpy-dev/reference/arrays.nditer.html

是一个很好的 nditer 教程。最后的 cython 部分是最好的部分。

关于python - 如何在numpy中指定迭代器的深度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31151913/

相关文章:

python - 使用 Pandas 将值与日期数据类型分开

python - 保存时计算字段值?

javascript - jScript - 如何 "mirror"矩阵(多维数组)

arrays - Swift 3 - 将用户输入添加到数组并选择随机项目

python - 如何强制二阶 polyfit 的 y 截距为 0

python - 使用 numpy、pandas 和 scikit-learn 等依赖包运行 pyspark

python - 颜色并不一致地应用于子图中的类别

python - 如何将关键字参数传递给 reactor.callLater

python - 更改变量时公式无法正确翻译

Java:从计算的角度来看,如果将一个数组设置为对另一个数组的引用会怎样?