Numpy Quick Tutorial

What is Numpy?

  • Numpy is an extension library (package) for Python.
  • Numpy is written specifically to work with multidimensional arrays (All the elements of the array should be the same type).
  • Numpy is designed for scientific computing.

Basics

  • Numpy's main class is ndarray which also has an alias array.
  • Useful attributes of an ndarray object are:

    • ndarray.ndim: the number of dimensions of the array.

    • ndarray.shape: A tuple of integers showing the size of the array in each dimension.

    • ndarray.size: Total number of elements in the array.

    • ndarray.dtype: Type of the array elements.

How to create arrays

  • Arrays can be created from Python sequences such as a list or a tuple. The type of resulting array depends on the type of elements in the sequences. ### Examples
In [2]:
import numpy as np
x=[1,2,5,3,6, 4 ,5 ]
y=np.array(x)
z=np.array([[1,2,3],[9,8,7]]) # Create an array from a list
print(x)
print(y)
print (type(x))
print(type(y))
print(z)
[1, 2, 5, 3, 6, 4, 5]
[1 2 5 3 6 4 5]
<class 'list'>
<class 'numpy.ndarray'>
[[1 2 3]
 [9 8 7]]
In [21]:
np.array(((1,2,3),(9,8,7))) # Create an array from a tuple
Out[21]:
array([[1, 2, 3],
       [9, 8, 7]])
In [4]:
a = np.array([[1.0,2,3],[9,8,7]]) # Type of array will be float
a.dtype
print(a)
[[ 1.  2.  3.]
 [ 9.  8.  7.]]
In [23]:
a = np.array([[1,2,3],[9,8,7]],dtype=float) # Specify type explicitly
a.dtype
Out[23]:
dtype('float64')
  • The function zero creates arrays of zeros.
In [2]:
np.zeros((3,7)) # Create array of zeros
Out[2]:
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]])
  • The function ones creates arrays of ones.
In [25]:
np.ones((3,2)) # Create array of ones
Out[25]:
array([[ 1.,  1.],
       [ 1.,  1.],
       [ 1.,  1.]])
  • The function arange creates sequence of numbers.
In [3]:
np.arange( 0, 1.1, .2 ) # Create array from a sequence of numbers
Out[3]:
array([ 0. ,  0.2,  0.4,  0.6,  0.8,  1. ])
  • The function linspace can also create sequence of numbers.
In [27]:
np.linspace(.1,.7,5 ) # Create 5 linearly spaced numbers from .1 to .7
Out[27]:
array([ 0.1 ,  0.25,  0.4 ,  0.55,  0.7 ])

</p>

Array creation functions

FunctionDescription
arrayConvert input data (list, tuple, or other sequence type) to an ndarray either by inferring a dtype or explicitly specifying a dtype. Copies the input data by default.
asarrayConvert input to ndarray, but do not copy if the input is already an ndarray
arangeLike the built-in range but returns an ndarray instead of a list.
onesProduce an array of all 1’s.
ones_likeProduces a ones array of the same shape and data type as the given array
zerosProduce an array of all 0's.
zeros_likeProduces an array of all zeros of the same shape and data type as the given array
identityCreate a square identity matrix
</div></div>

Shape Manipulation

  • The function reshape changes the shape of an array.
In [28]:
a=np.linspace(1,6,6 ) # Create a 1 by 6 array
b=a.reshape(3,2) # Reshape the array into a 3 by 2 array
print("a = ",a)
print("b = ",b)
a =  [ 1.  2.  3.  4.  5.  6.]
b =  [[ 1.  2.]
 [ 3.  4.]
 [ 5.  6.]]
  • The function ravel flattens an array.
In [4]:
a = np.array([[1,2,3],[9,8,7]]) # create a 2 by 3 array
b=a.ravel()
print("a = ",a)
print("b = ",b)
a =  [[1 2 3]
 [9 8 7]]
b =  [1 2 3 9 8 7]

Universal Functions

  • Universal functions are familiar functions such as sin, cos, exp. sqrt. These functions operate elementwise on an array and produce another array as output.
In [30]:
a = np.array([[1,2,3],[9,8,7]]) # create a 2 by 3 array
b = np.sin(a)
print (b)
[[ 0.84147098  0.90929743  0.14112001]
 [ 0.41211849  0.98935825  0.6569866 ]]

Basic Array Operations

NOTE : All arithmetic operations in numpy are applied elementwise. This includes multiplication and division of arrays. The matrix product of two arrays should be performed by using the dot function.

  • Scalar operations
In [31]:
a = np.array([1, 2, 3, 4])
a+5  # Scalar, 5, is added to every element of array
Out[31]:
array([6, 7, 8, 9])
In [32]:
a = np.array([1, 2, 3, 4])
a*3  # Every element of array is multiplied by the scalar
Out[32]:
array([ 3,  6,  9, 12])
In [33]:
a = np.array([1, 2, 3, 4])
a/3.0  # Every element of array is divided by the scalar
Out[33]:
array([ 0.33333333,  0.66666667,  1.        ,  1.33333333])
  • Elementwise Array operations
In [5]:
a=np.array([[1,2,3],[9,8,7]])
b=np.array([[6,5,4],[2,4,6]])
print(a)
print(b)
c=a*b # Elementwise multiplication
d=np.dot(a,b)
print(c)
print(d)
[[1 2 3]
 [9 8 7]]
[[6 5 4]
 [2 4 6]]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-ffce90ef95f7> in <module>()
      4 print(b)
      5 c=a*b # Elementwise multiplication
----> 6 d=np.dot(a,b)
      7 print(c)
      8 print(d)

ValueError: shapes (2,3) and (2,3) not aligned: 3 (dim 1) != 2 (dim 0)
In [35]:
a=np.array([[1,2,3],[9,8,7]])
b=np.array([[6,5,4],[2,4,6]])
a/b # Elementwise division
Out[35]:
array([[ 0.16666667,  0.4       ,  0.75      ],
       [ 4.5       ,  2.        ,  1.16666667]])
  • Mathematical Array operations vs. Elementwise Array operations
In [36]:
a=np.array([[1,2],[9,8]])
b=np.array([[6,5],[2,4]])
c=a*b # Elementwise multiplication
d=np.dot(a,b) # Mathematical multiplication
print("c = ",c)
print("d = ",d)
c =  [[ 6 10]
 [18 32]]
d =  [[10 13]
 [70 77]]

Broadcasting

Broadcasting is Numpy's terminology for performing mathematical operations between arrays with different shapes.

Broadcasting Rules

  1. If all input arrays do not have the same number of dimensions, a “1” will be repeatedly prepended to the shapes of the smaller arrays until all the arrays have the same number of dimensions.

  2. If an array has a size of 1 along a particular dimension it acts as if it has the size of the largest shape along that dimension by copying along that dimension.

In [7]:
a=np.array([[[1,3,4],[9,8, 5]],[[2,1,5],[8,6,2]]])
b=np.array([6,5,3])
print(np.shape(a))
print(np.shape(b))
print(a+b) # Elementwise addition with broadcasting
print("------------------\n",a[0])
(2, 2, 3)
(3,)
[[[ 7  8  7]
  [15 13  8]]

 [[ 8  6  8]
  [14 11  5]]]
------------------
 [[1 3 4]
 [9 8 5]]

Explanation:

Rule 1: Array a's shape is (2,2,3) and array b's shape is (3,). According to rule 1 of broadcasting a 1 is prepended to the shape of array b until it has the same dimensions as array a i.e. (1,1,3).

Rule 2: Array b is extended along the dimensions which have size 1 by copying the array as many time as needed until it is the same size as array a. This makes the size of array b to be (2,2,3) and its content to be [[[6,5,3],[6,5,3]],[[6,5,3],[6,5,3]]].

After applying the broadcasting rules, the two arrays are the same size and elementwise add operation is performed.

Below is another example of broadcasting in numpy

In [38]:
a=np.array([[1],[2],[3]])
print(np.shape(a))
b=np.array([4,5,6])
a*b # Elementwise multiplication with broadcasting
(3, 1)
Out[38]:
array([[ 4,  5,  6],
       [ 8, 10, 12],
       [12, 15, 18]])