【问题标题】:How to reshape an array in Python using Numpy?如何使用 Numpy 在 Python 中重塑数组?
【发布时间】:2019-08-25 21:39:32
【问题描述】:

我有一个 (10,) 数组,我想在 (1,10) 中重塑

我做了以下(你是我的数组)

import numpy as np

u = u.reshape(-1,1).T

但它不起作用,有什么建议吗?

【问题讨论】:

标签: python numpy


【解决方案1】:

我认为@Chris在评论中提到的很好,你可以试试

我已经尝试过这个场景

>>> import numpy as np
>>> u = np.zeros((10))

>>> u.shape
(10,)
>>> u.T
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
>>> u = u.reshape(1, -1)
>>> u.shape
(1, 10)
>>> u.T
array([[0.],
   [0.],
   [0.],
   [0.],
   [0.],
   [0.],
   [0.],
   [0.],
   [0.],
   [0.]])

我认为对于您的情况,u.reshape(1, -1) 可以完成您的工作。

【讨论】:

    【解决方案2】:

    本书中另一个有效的技巧是np.newaxis

     u = u[np.newaxis,:]
    

    应该给你一个形状为(1,10)的数组

    【讨论】:

      【解决方案3】:

      正如 Chris 在他的评论中提到的,您只是想通过将行数固定为 1 和 let Python figure out the other dimension 来重塑数组:

      u=u.reshape(1, -1)
      

      【讨论】:

        【解决方案4】:

        你想要的是:

        u = u.reshape((-1, 1)).T
        

        【讨论】:

          【解决方案5】:

          你可以尝试使用expand_dims()方法。

          import numpy as np
          
          a = np.zeros(10) # a.shape = (10,)
          a = np.expand_dims(a, axis=0)
          print(a.shape)
          

          输出

          (1, 10)
          

          【讨论】:

            猜你喜欢
            • 2019-05-05
            • 2017-07-22
            • 1970-01-01
            • 2011-10-01
            • 1970-01-01
            • 2020-07-11
            • 1970-01-01
            • 2013-01-06
            • 2020-11-26
            相关资源
            最近更新 更多