简体   繁体   中英

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

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)

Use x = rd.reshape((-1,3)) . The -1 says "make this whatever is leftover after the other axes are satisfied".

TL;DR column = row[:, None]


The fundamental flaw in your understanding is naming a Numpy array a row matrix . 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.

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.

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)

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. 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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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