【问题标题】:Python: Is there an inverse for ndarray.flatten('F')?Python:ndarray.flatten('F') 有逆向吗?
【发布时间】:2011-02-23 03:46:06
【问题描述】:

例如:

from numpy import *
x = array([[1,2], [3, 4], [5, 6]])
print x.flatten('F')
>>>[1 3 5 2 4 6]

是否可以从[1 3 5 2 4 6]得到[[1,2], [3, 4], [5, 6]]

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:
    >>> a = numpy.array((1, 3, 5, 2 ,4, 6))
    >>> a.reshape(2, -1).T
    array([[1, 2],
           [3, 4],
           [5, 6]])
    >>> 
    

    【讨论】:

      【解决方案2】:

      这似乎更简单一些。只需将原始形状传回重塑即可。

      import numpy as np
      np.array([[1,2], [3, 4], [5, 6]]).flatten().reshape((3, 2))
      

      array([[1, 2],
             [3, 4],
             [5, 6]])
      

      对于您的 Fortran 排序,将“F”传递给重塑顺序:

      import numpy as np
      np.array([[1,2], [3, 4], [5, 6]]).flatten('F').reshape((3, 2), order='F')
      

      array([[1, 2],
             [3, 4],
             [5, 6]])
      

      【讨论】:

        【解决方案3】:

        对于任何寻找优雅的纯 python oneliner 来解决这个问题的人:

        arr2d = [[arr1d[i+j*width] for i in range(width)] for j in range(height)]
        

        【讨论】:

        • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
        猜你喜欢
        • 2010-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多