1 min read

Python NumPy Module

NumPy (Numerical Python) is the fundamental package for scientific computing in Python. It provides a high-performance multidimensional array object and tools for working with these arrays.

Installation

pip install numpy

Importing the Module

Standard convention is to import it as np.

import numpy as np

Creating Arrays

NumPy arrays are faster and more compact than Python lists.

# From a list
arr = np.array([1, 2, 3])

# 2D Array (Matrix)
matrix = np.array(<a href='/1%2C%202%2C%203%5D%2C%20%5B4%2C%205%2C%206'>1, 2, 3], [4, 5, 6</a>)

# Range of values (start, stop, step)
r = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]

# Linear space (start, stop, number of items)
l = np.linspace(0, 1, 5) # [0., 0.25, 0.5, 0.75, 1.]

# Zeros and Ones
z = np.zeros((2, 3)) # 2x3 matrix of zeros
o = np.ones((2, 3))  # 2x3 matrix of ones

Array Inspection

a = np.array(<a href='/1%2C%202%2C%203%5D%2C%20%5B4%2C%205%2C%206'>1, 2, 3], [4, 5, 6</a>)

print(a.ndim)   # 2 (Dimensions)
print(a.shape)  # (2, 3) (Rows, Columns)
print(a.size)   # 6 (Total elements)
print(a.dtype)  # int64 (Data type)

Operations

Operations are element-wise by default.

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

print(a + b)  # [5, 7, 9]
print(a * b)  # [4, 10, 18]
print(a * 2)  # [2, 4, 6] (Broadcasting)

Indexing and Slicing

a = np.array(<a href='/1%2C%202%2C%203%5D%2C%20%5B4%2C%205%2C%206'>1, 2, 3], [4, 5, 6</a>)

# Element at row 0, column 1
print(a[0, 1]) # 2

# Slice: All rows, column 1
print(a[:, 1]) # [2, 5]

Basic Statistics

a = np.array(<a href='/1%2C%202%2C%203%5D%2C%20%5B4%2C%205%2C%206'>1, 2, 3], [4, 5, 6</a>)

print(np.mean(a))       # 3.5
print(np.max(a))        # 6
print(np.sum(a, axis=0)) # [5, 7, 9] (Sum columns)

programming/python/python