逐列遍历numpy数组 [英] Iterate over numpy array columnwise

查看:730
本文介绍了逐列遍历numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

np.nditer自动逐行迭代数组的元素.有没有一种方法可以按列迭代数组的元素?

np.nditer automatically iterates of the elements of an array row-wise. Is there a way to iterate of elements of an array columnwise?

x = np.array([[1,3],[2,4]])

for i in np.nditer(x):
    print i

# 1
# 3
# 2
# 4

我想要的是:

for i in Columnwise Iteration(x):
    print i
# 1
# 2
# 3
# 4

我最好的选择只是在进行迭代之前转置数组吗?

Is my best bet just to transpose my array before doing the iteration?

推荐答案

出于完整性考虑,在遍历元素之前不必一定要转置矩阵.使用np.nditer,您可以指定如何遍历矩阵的顺序.默认通常是行优先或类似C的顺序.您可以覆盖此行为,然后选择所需的列大顺序或类似 FORTRAN 的顺序.只需指定一个附加参数order,并在使用np.nditer时将此标志设置为'F':

For completeness, you don't necessarily have to transpose the matrix before iterating through the elements. With np.nditer you can specify the order of how to iterate through the matrix. The default is usually row-major or C-like order. You can override this behaviour and choose column-major, or FORTRAN-like order which is what you desire. Simply specify an additional argument order and set this flag to 'F' when using np.nditer:

In [16]: x = np.array([[1,3],[2,4]])

In [17]: for i in np.nditer(x,order='F'):
   ....:     print i
   ....:     
1
2
3
4

您可以在此处详细了解如何控制迭代顺序: http://docs.scipy.org/doc/numpy-1.10.0/reference/arrays.nditer.html#controlling-iteration-order

You can read more about how to control the order of iteration here: http://docs.scipy.org/doc/numpy-1.10.0/reference/arrays.nditer.html#controlling-iteration-order

这篇关于逐列遍历numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆