Numpy Overview

  • Scientific computing package for Python
  • Arrays are the fundamental elements
  • Methods to manipulate and perform mathematical operations on arrays and matrices
  • Documentation: https://docs.scipy.org/doc/

Import the Numpy Package

  • Must import numpy package before use
  • Import as 'np' and then call using np.<>

In [33]:
import numpy as np

Create Basic Arrays


In [2]:
A = np.array([[1,2,3]]); print(A)


[[1 2 3]]

In [3]:
B = np.array([[1,2,3],[4,5,6],[7,8,9]]); print(B)


[[1 2 3]
 [4 5 6]
 [7 8 9]]

In [4]:
C = np.zeros((2,1)); print(C)


[[ 0.]
 [ 0.]]

In [5]:
D = np.ones((1,3)); print(D)


[[ 1.  1.  1.]]

In [6]:
E = np.random.randn(3,3); print(E)


[[ 0.71722718  0.62570159  0.39517151]
 [ 0.91379584 -0.41934408  0.66504493]
 [-1.50850069  0.2865281  -0.8727147 ]]

Array Indexing


In [7]:
print(B)


[[1 2 3]
 [4 5 6]
 [7 8 9]]

In [41]:
B[0]  #first row


Out[41]:
array([1, 2, 3])

In [42]:
B[:,0] #first column


Out[42]:
array([1, 4, 7])

In [9]:
B[0,0]


Out[9]:
1

In [10]:
B[2,2]


Out[10]:
9

In [11]:
B[:,0]


Out[11]:
array([1, 4, 7])

Array Attributes


In [12]:
print(B.dtype)
print(B.shape)
print(B.ndim)
print(B.size)


int32
(3, 3)
2
9

Array Methods


In [13]:
B.tolist()


Out[13]:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In [14]:
B.T


Out[14]:
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])

In [15]:
B.reshape(1,9)


Out[15]:
array([[1, 2, 3, 4, 5, 6, 7, 8, 9]])

In [16]:
B.flatten()


Out[16]:
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

In [17]:
A.nonzero()


Out[17]:
(array([0, 0, 0], dtype=int64), array([0, 1, 2], dtype=int64))

Array Calcuations


In [18]:
A


Out[18]:
array([[1, 2, 3]])

In [19]:
A.min()


Out[19]:
1

In [20]:
A.max()


Out[20]:
3

In [21]:
A.sum()


Out[21]:
6

In [22]:
A.mean()


Out[22]:
2.0

In [23]:
A.var()


Out[23]:
0.66666666666666663

In [24]:
A.std()


Out[24]:
0.81649658092772603

Array Arithmetic

  • numpy performs element-wise arithmetic

In [25]:
A


Out[25]:
array([[1, 2, 3]])

In [26]:
A*A


Out[26]:
array([[1, 4, 9]])

In [27]:
A**A


Out[27]:
array([[ 1,  4, 27]], dtype=int32)

In [28]:
A/A


Out[28]:
array([[ 1.,  1.,  1.]])

In [29]:
A-A


Out[29]:
array([[0, 0, 0]])

In [30]:
A+A


Out[30]:
array([[2, 4, 6]])

In [31]:
A<B


Out[31]:
array([[False, False, False],
       [ True,  True,  True],
       [ True,  True,  True]], dtype=bool)

In [32]:
A==B


Out[32]:
array([[ True,  True,  True],
       [False, False, False],
       [False, False, False]], dtype=bool)