Array shapes in numpy


In [1]:
import os
setup_script = os.path.join(os.environ['ENV_JUPYTER_SETUPS_DIR'], 'setup_sci_env_basic.py')
%run $setup_script


The autoreload extension is already loaded. To reload it, use:
  %reload_ext autoreload

In [2]:
a = np.array([2.0, 3.0, 4.0, 5.0])
b = np.array([[2.0], [3.0], [4.0], [5.0]])

shape: (4,)


In [3]:
a


Out[3]:
array([ 2.,  3.,  4.,  5.])

In [4]:
a.shape


Out[4]:
(4,)

In [5]:
a.flags


Out[5]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

In [6]:
a.itemsize


Out[6]:
8

In [7]:
a.strides


Out[7]:
(8,)

Accessing an element


In [8]:
a[0]


Out[8]:
2.0

In [9]:
a[0,0]


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-9-6d5034879124> in <module>()
----> 1 a[0,0]

IndexError: too many indices for array

shape: (4,1)


In [10]:
b


Out[10]:
array([[ 2.],
       [ 3.],
       [ 4.],
       [ 5.]])

In [11]:
b.shape


Out[11]:
(4, 1)

In [12]:
b.flags


Out[12]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

In [13]:
b.itemsize


Out[13]:
8

In [14]:
b.strides


Out[14]:
(8, 8)

In [15]:
b[0]


Out[15]:
array([ 2.])

In [16]:
b[0,0]


Out[16]:
2.0

Operating with different shapes


In [17]:
a + b


Out[17]:
array([[  4.,   5.,   6.,   7.],
       [  5.,   6.,   7.,   8.],
       [  6.,   7.,   8.,   9.],
       [  7.,   8.,   9.,  10.]])

In [18]:
a * b


Out[18]:
array([[  4.,   6.,   8.,  10.],
       [  6.,   9.,  12.,  15.],
       [  8.,  12.,  16.,  20.],
       [ 10.,  15.,  20.,  25.]])

In [19]:
a.dot(b)


Out[19]:
array([ 54.])

shape: (2,2)


In [20]:
c = a.reshape(2,2)

In [21]:
c


Out[21]:
array([[ 2.,  3.],
       [ 4.,  5.]])

In [22]:
d = b.reshape(2,2)

In [23]:
d


Out[23]:
array([[ 2.,  3.],
       [ 4.,  5.]])

Dot product


In [24]:
M = np.array([[2.0, 3.0, 3.0, 4.0], [9.0, 5.0, 1.0, 1.0], [2.0, 4.0, 5.0, 9.0], [8.0, 3.0, 4.0, 5.0]])

In [25]:
M


Out[25]:
array([[ 2.,  3.,  3.,  4.],
       [ 9.,  5.,  1.,  1.],
       [ 2.,  4.,  5.,  9.],
       [ 8.,  3.,  4.,  5.]])

In [26]:
M.dot(a)


Out[26]:
array([ 45.,  42.,  81.,  66.])

In [27]:
M.dot(b)


Out[27]:
array([[ 45.],
       [ 42.],
       [ 81.],
       [ 66.]])