Home > Mobile >  How are elements across Rows(r) and columns (c) arranged in numpy?
How are elements across Rows(r) and columns (c) arranged in numpy?

Time:09-17

I have started learning about numpy and I was going through some simple examples where I came across changing shapes of numpy array. How do we interpret numpy arrays in terms of matrices?

If I have an example -

import numpy as np 
a = np.zeros(5)
a.shape 

returns (5,)

print(a) returns

array([0., 0., 0., 0., 0.])

Does this mean it has 5 rows and 1 column or 5 columns and 1 row?

Moreover, if I write

a.shape = (5,1)
print(a)
array([[0.],
       [0.],
       [0.],
       [0.],
       [0.]])

I am little confused with the shapes of numpy arrays in general. Any help is appreciated.

CodePudding user response:

In numpy, the shape tuple returns a tuple (m, n), m refers to the "number of rows", whereas n refers to the number of columns.

So (5, 1) would be 5 rows and one column.

And (5,) is just a 1d array, 5 rows... But a 1d vector doesn't isn't referred by the number of columns and rows, since it isn't nested. It's just an array with five elements.

As @TimRoberts mentioned, numpy arrays can have an arbitrary number of dimensions. Such as images, with a shape of a tuple with 3 elements, which is rows, columns and channels, for RGB it would have 3 channels, and for RGBA it would be 4 channels. This would be an example of an 3d array.

CodePudding user response:

The format is (m, n) where m is the number of rows and n is the number of columns for a 2d array.

HOWEVER your case is a 1d array, which is why you get (m,). This basically means it's neither rows nor columns, just five items, like a list. There is no second dimension in this case. If you wanted to add a second dimension, there are a bunch of functtions that just happen to slip my mind

CodePudding user response:

Lets make a 1d array with 12 items:

In [150]: a = np.arange(12)
In [151]: a
Out[151]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

reshape to 2d. This is view, shape is different, but it shares the data-buffer.

In [152]: a.reshape(3,4)
Out[152]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

another view, 3d:

In [153]: a.reshape(2,3,2)
Out[153]: 
array([[[ 0,  1],
        [ 2,  3],
        [ 4,  5]],

       [[ 6,  7],
        [ 8,  9],
        [10, 11]]])

again a 2d view:

In [154]: a.reshape(6,2)
Out[154]: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11]])

or a 3d:

In [155]: a.reshape(1,1,12)
Out[155]: array([[[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11]]])

a.reshape(1,12,1,1) would take up more space. :)

and to confuse you further a view with a different order:

In [156]: a.reshape(3,4, order='F')
Out[156]: 
array([[ 0,  3,  6,  9],
       [ 1,  4,  7, 10],
       [ 2,  5,  8, 11]])
  • Related