【问题标题】:numpy.ndenumerate to return indices in Fortran order?numpy.ndenumerate 以 Fortran 顺序返回索引?
【发布时间】:2013-08-19 18:38:37
【问题描述】:

当使用numpy.ndenumerate 时,索引按照C-contiguous 数组顺序返回,例如:

import numpy as np
a = np.array([[11, 12],
              [21, 22],
              [31, 32]])

for (i,j),v in np.ndenumerate(a):
    print i, j, v

如果a 中的order'F''C',则不行,这给出:

0 0 11
0 1 12
1 0 21
1 1 22
2 0 31
2 1 32

numpy 中是否有任何内置迭代器,例如 ndenumerate 来给出这个(在数组 order='F' 之后):

0 0 11
1 0 21
2 0 31
0 1 12
1 1 22
2 1 32

【问题讨论】:

    标签: python arrays numpy iterator iteration


    【解决方案1】:

    您可以使用np.nditer 进行如下操作:

    it = np.nditer(a, flags=['multi_index'], order='F')
    while not it.finished:
        print it.multi_index, it[0]
        it.iternext()
    

    np.nditer 是一个非常强大的野兽,它暴露了 Python 中的一些内部 C 迭代器,请查看文档中的 Iterating Over Arrays

    【讨论】:

    • 糟糕!刚刚在循环中添加了it.iternext() 以使迭代前进......
    • 我认为for item in it 也可以。我不清楚为什么文档选择这种特殊的方式来推进迭代器。你呢?
    • 没有线索。直到今天,我想我还没有尝试在 Python 中使用 nditer...
    【解决方案2】:

    只需进行转置即可满足您的需求:

    a = np.array([[11, 12],
                  [21, 22],
                  [31, 32]])
    
    for (i,j),v in np.ndenumerate(a.T):
        print j, i, v
    

    结果:

    0 0 11
    1 0 21
    2 0 31
    0 1 12
    1 1 22
    2 1 32
    

    【讨论】:

    • 是的,这肯定更好:)
    • @Akavall 很棒的收获!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 2021-01-05
    • 2021-09-29
    • 1970-01-01
    • 2013-08-30
    相关资源
    最近更新 更多