Numpy Basics

In this Numpy cheatsheet, we will go through basics of Numpy.

In [1]:
import pandas as pd
import numpy as np

Numpy Arrays

Create Numpy Array

In [2]:
arr = np.array([10,11,12,14])

Find the length of numpy array.

In [3]:
len(arr)
Out[3]:
4
In [4]:
arr[1]
Out[4]:
11

Find type of numpy array.

In [5]:
type(arr[1])
Out[5]:
numpy.int64
In [6]:
arr.dtype
Out[6]:
dtype('int64')

Create Numpy array with int32 type

In [7]:
arr = np.array([10,11,12],dtype=np.int32)
In [8]:
arr.dtype
Out[8]:
dtype('int32')
In [9]:
arr1 = np.random.rand(10000000)
arr2 = np.random.rand(10000000)

Multiply Two Numpy Arrays

In [10]:
%time arr1 * arr2
CPU times: user 9.09 ms, sys: 19.1 ms, total: 28.2 ms
Wall time: 26.5 ms
Out[10]:
array([0.25840502, 0.25775087, 0.41021642, ..., 0.20744659, 0.31897789,
       0.24688618])

Numpy Matrix

In [11]:
mat = np.array([[10,20,30],[1,2,3]])
In [12]:
mat
Out[12]:
array([[10, 20, 30],
       [ 1,  2,  3]])

Find shape of Numpy Matrix...

In [13]:
mat.shape
Out[13]:
(2, 3)

Numpy matrix last row access...

In [14]:
mat[-1]
Out[14]:
array([1, 2, 3])

Create numbers Using Numpy np.arange

In [15]:
nos = np.arange(6)

nos = np.arange(6)

Reshape Numpy Matrix

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

Transpose Numpy Matrix

In [17]:
nos = np.arange(6)
nos.transpose()
Out[17]:
array([0, 1, 2, 3, 4, 5])
In [18]:
nos.T
Out[18]:
array([0, 1, 2, 3, 4, 5])

Numpy Matrix Slicing

In [19]:
mat = np.array([[10,20,30],[1,2,3]])
In [20]:
mat
Out[20]:
array([[10, 20, 30],
       [ 1,  2,  3]])

Access first row and second column values...

In [22]:
mat[0,1]
Out[22]:
20

Access 2nd column values...

In [25]:
mat[:,1]
Out[25]:
array([20,  2])

Access all column values except values from first column...

In [28]:
mat[:,1:]
Out[28]:
array([[20, 30],
       [ 2,  3]])

Access values from column 2nd,3rd which are from row 2nd...

In [29]:
mat[1:,1:]
Out[29]:
array([[2, 3]])

Also we can use transpose method on the above sliced matrix...

In [33]:
mat[1:,1:].transpose()
Out[33]:
array([[2],
       [3]])