简体   繁体   English

无法将 numpy 行矩阵重塑为列矩阵

[英]Unable to reshape numpy row matrix into column matrix

This is a very simple exercise where I need to change my row into column, but seems like it's not that simple in python这是一个非常简单的练习,我需要将行更改为列,但在 python 中似乎没那么简单

import numpy as np

rd = np.zeros(3)
normal = 0
for i in range(len(rd)):
    rd[i]= randrange(0,10)
    normal += rd[i]

for i in range(len(rd)):
    rd[i] = round(rd[i]/normal,3)
print(rd.shape)
x = rd.reshape((0,3))
print(x.shape)

Getting the error ValueError: cannot reshape array of size 3 into shape (0,3)获取错误ValueError: cannot reshape array of size 3 into shape (0,3)

Use x = rd.reshape((-1,3)) .使用x = rd.reshape((-1,3)) The -1 says "make this whatever is leftover after the other axes are satisfied". -1 表示“在满足其他轴后剩余的任何东西”。

TL;DR column = row[:, None] TL;DR column = row[:, None]


The fundamental flaw in your understanding is naming a Numpy array a row matrix .您理解中的根本缺陷是将 Numpy数组命名为行矩阵 Matrices are a well defined concept and are 2D in their nature, Numpy arrays can have as many dimension as needed, and this means also a single dimension, so what you call a row matrix is just a sequence of numbers of assigned length, not a 2D data structure.矩阵是一个定义明确的概念,本质上是 2D 的,Numpy 数组可以根据需要有任意多的维度,这也意味着一个维度,所以你所说的行矩阵只是一个指定长度的数字序列,而不是一个二维数据结构。

In [57]: a = np.arange(3)
    ...: print(a.shape, a)
(3,) [0 1 2]

Note that after the comma there is nothing , in Python (3,) is a tuple containing a single element.请注意,逗号之后没有任何内容,在 Python 中(3,)是一个包含单个元素的元组

To have a column matrix you have to change the number of dimensions to two, and this can be done using the .reshape() method of arrays — you want 3 rows and 1 column, so the target shape must be this tuple: (3, 1)要获得列矩阵,您必须将维数更改为 2,这可以使用数组的.reshape()方法来完成——您需要 3 行和 1 列,因此目标形状必须是这个元组: (3, 1)

In [58]: print(a.reshape((3,1)))
[[0]
 [1]
 [2]]

In [59]: b = a.reshape((3,1)) ; print(b)
[[0]
 [1]
 [2]]

So far, so good BUT sometimes you don't want to use explicitly the number of rows, so you may think, I'll use the colon notation到目前为止,很好,但有时您不想明确使用行数,所以您可能会想,我将使用冒号表示法

In [60]: a.reshape((:,1))
  File "<ipython-input-60-e69626de0272>", line 1
    a.reshape((:,1))
               ^
SyntaxError: invalid syntax

but alas, it doesn't work.但可惜,它不起作用。

Comes to rescue Numpy's extended indexing, using it we can introduce additional dummy indexes with length equal to 1, the syntax is to use either None or numpy.newaxis in addition to other indices.来拯救 Numpy 的扩展索引,使用它我们可以引入额外的长度等于 1 的虚拟索引,语法是除了其他索引之外使用Nonenumpy.newaxis An example is now overdue一个例子现在过期了

In [61]: a[:,None]
Out[61]: 
array([[0],
       [1],
       [2]])

In [62]: b = a[:,None] ; print(b)
[[0]
 [1]
 [2]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM