【问题标题】:How to change array shapes in in numpy?如何在numpy中更改数组形状?
【发布时间】:2015-06-05 13:49:04
【问题描述】:

如果我创建一个数组X = np.random.rand(D, 1),它的形状为(3,1)

[[ 0.31215124]
 [ 0.84270715]
 [ 0.41846041]]

如果我创建自己的数组A = np.array([0,1,2]),那么它的形状为(1,3),看起来像

[0 1 2]

如何在我的数组A 上强制使用形状(3, 1)

【问题讨论】:

  • 抱歉您在找A.reshape([3,1])

标签: python numpy


【解决方案1】:

您可以将形状元组直接分配给numpy.ndarray.shape

A.shape = (3,1)

【讨论】:

  • 也许有人对你对“功能”的使用很挑剔。 np.reshape 是函数,A.reshape 是方法,A.shape= 是功能?他们都做同样的工作。
  • 设置shape 有时会引发错误,不能保证在所有情况下都有效。只是添加信息,我不是反对票。
  • np.reshape 文档说:If you want an error to be raise if the data is copied, you should assign the new shape to the shape attribute of the array. a.shape= 并不总是有效的事实可能是一件好事。您还有其他案例吗?
  • docs.scipy.org/doc/numpy/reference/generated/… 没有给出任何关于.shape= 何时出错的警告。
【解决方案2】:
A=np.array([0,1,2])
A.shape=(3,1)

A=np.array([0,1,2]).reshape((3,1))  #reshape takes the tuple shape as input

【讨论】:

    【解决方案3】:

    numpy 模块有一个reshape 函数,而ndarray 有一个reshape 方法,这两种方法都应该可以创建一个你想要的形状的数组:

    import numpy as np
    A = np.reshape([1, 2, 3, 4], (4, 1))
    # Now change the shape to (2, 2)
    A = A.reshape(2, 2)
    

    Numpy 会检查数组的大小没有改变,即prod(old_shape) == prod(new_shape)。由于这种关系,您可以将 shape 中的一个值替换为 -1,numpy 会为您解决:

    A = A.reshape([1, 2, 3, 4], (-1, 1))
    

    【讨论】:

      【解决方案4】:

      您可以直接设置形状,即

      A.shape = (3L, 1L)
      

      或者你可以使用调整大小功能:

      A.resize((3L, 1L))
      

      或在创建过程中使用 reshape

      A = np.array([0,1,2]).reshape((3L, 1L))
      

      【讨论】:

      • 应避免分配给shaperesize,除非您知道自己在做什么,因为它们都有可能让新用户感到惊讶的行为。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 2018-04-07
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多