[英]Iterate over two numpy 2d matrices using nditer
我正在尝试迭代两个numpy矩阵,其中一个大小为nx3,另一个大小为nx1
我试图让nditer同时迭代他们的行。
因此,如果我们有:
y = np.array([ [ 1],
[-1],
[ 1] ])
x = np.array([[ 1.3432504 , -1.3311479 , 1. ],
[ 1.8205529 , -0.6346681 , 1. ],
[ 0.98632067, -1.8885762 , 1. ]])
我尝试:
for (a,b) in iterator:
print(a)
print(b)
这应该给
[1]
[ 1.3432504 , -1.3311479 , 1. ]
[-1]
[ 1.8205529 , -0.6346681 , 1. ]
[1]
[ 0.98632067, -1.8885762 , 1. ]
我用'external_loop flag'尝试了np.nditer,我得到了x的期望输出,但是当我一次只想要一个元素时,它会迫使y分成3个元素。
先感谢您。
您可以使用zip()
内置函数:
In [22]: for i, j in zip(y, x):
print(i);print(j)
....:
[1]
[ 1.3432504 -1.3311479 1. ]
[-1]
[ 1.8205529 -0.6346681 1. ]
[1]
[ 0.98632067 -1.8885762 1. ]
使用nditer
很难控制迭代的“深度”。 例如最简单的情况:
In [35]: for i,j in np.nditer([y, x]):
...: print(i, j)
...:
1 1.3432504
1 -1.3311479
1 1.0
-1 1.8205529
-1 -0.6346681
-1 1.0
1 0.98632067
1 -1.8885762
1 1.0
这(i,j) pair of values for each broadcastable combination of
y and
x的(i,j) pair of values for each broadcastable combination of
创建一对(i,j) pair of values for each broadcastable combination of
.
x is (3, 3),
y is (3,1)
,结果是(3,3).flat上的迭代。
(如果x
为np.arange(n)
,则nditer
会生成(3,1)数组与(1,n),即(3,n)集的所有组合。
您不能轻易告诉nditer
仅在x
的行上进行迭代。 external_loop
可以做到,但不可预测。
ndindex
生成给定深度的索引,但是它是通过创建正确形状的数组来实现的。
In [38]: for i,j in np.ndindex(2,3):
...: print(i,j)
...:
0 0
0 1
0 2
1 0
1 1
1 2
或迭代2个数组的行:
In [39]: for i in np.ndindex(3):
...: print(y[i], x[i,:])
...:
[1] [[ 1.3432504 -1.3311479 1. ]]
[-1] [[ 1.8205529 -0.6346681 1. ]]
[1] [[ 0.98632067 -1.8885762 1. ]]
但是您也可以for i in range(3):
很好地使用。
np.nditer
是开发cython
或其他c-api
代码的垫脚石。 nditer
的c-api版本具有nditer
的功能,并且速度相对较好。 python等效项既不快速也不强大。
您的评论提到了与apply_along_axis
进一步接口。 那是用Python编写的,并使用ndindex
为需要迭代的轴生成索引。 它可以使某些任务更方便,但不会加快代码的速度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.