Numpy Basics

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

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

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 19.4 ms, sys: 939 ┬Ás, total: 20.3 ms
Wall time: 19.7 ms
Out[10]:
array([0.04454974, 0.39669552, 0.71391548, ..., 0.25065678, 0.01203942,
       0.11915787])

Convert Numpy (np) Array To list

In [11]:
arr = np.array([10, 21, 3])
list1 = arr.tolist()
print(f'List: {list1}')
List: [10, 21, 3]

Convert Multi-Dimensional Numpy Array To List

In [12]:
import numpy as np
# 2d array to list
arr = np.array([[11, 100, 7], [14, 6, 2]]) 
list1 = arr.tolist() 
print(f'NumPy Array:\n{arr}') 
print(f'List: {list1}')
NumPy Array:
[[ 11 100   7]
 [ 14   6   2]]
List: [[11, 100, 7], [14, 6, 2]]

Python List To Numpy Array

In [13]:
l = [4,8,9]
arr = np.array(l)
print(arr)
[4 8 9]

Numpy Matrix

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

Find shape of Numpy Matrix...

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

Numpy matrix last row access...

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

Create numbers Using Numpy np.arange

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

Reshape Numpy Matrix

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

Transpose Numpy Matrix

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

Numpy Matrix Slicing

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

Access first row and second column values...

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

Access 2nd column values...

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

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

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

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

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

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

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