This guide covers the creation, manipulation, and operations of NumPy arrays, including indexing, reshaping, concatenation, splitting, copying, and aggregation.
Creating Arrays
Using np.array()
NumPy arrays have uniform data types. If mixed types are provided, they are converted to the highest priority type: str > float > int.
import numpy as np
lst = [1, 2, 3, 4, 5, 6]
arr = np.array(lst)
print(arr, type(arr)) # [1 2 3 4 5 6] <class 'numpy.ndarray'>
# Type precedence
arr = np.array([3.14, 2, 1, 'fg'])
print(arr) # ['3.14' '2' '1' 'fg']
Using NumPy Functions
- Ones:
np.ones(shape, dtype=None) - Zeros:
np.zeros(shape, dtype=None) - Full:
np.full(shape, fill_value, dtype=None) - Identity Matrix:
np.eye(N, M=None, k=0, dtype=float) - Linearly Spaced:
np.linspace(start, stop, num=50, endpoint=True, dtype=None) - Range:
np.arange([start,]stop[, step,], dtype=None) - Random Integers:
np.random.randint(low, high=None, size=None, dtype=int) - Standard Normal Distribution:
np.random.randn(d0, d1, ..., dn) - Normal Distribution:
np.random.normal(loc=0.0, scale=1.0, size=None) - Random Floats:
np.random.random(size=None)ornp.random.rand(*d0, d1, ..., dn)
n = np.ones((2, 3), dtype=int)
print(n)
n = np.full((2, 3, 4), 1)
print(n)
n = np.eye(3, 3, k=1, dtype=int)
print(n)
n = np.linspace(0, 100, num=51, dtype=int)
print(n)
n = np.arange(1, 10, 2)
print(n) # [1 3 5 7 9]
n = np.random.randint(0, 10, (2, 3))
print(n)
n = np.random.normal(170, 5, (3, 4))
print(n)
n = np.random.rand(3, 4)
print(n)
Array Properties
n = np.array([[[1, 2], [3, 4], [5, 6]]])
print(n.ndim) # 3
print(n.shape) # (1, 3, 2)
print(n.size) # 6
print(n.dtype) # int64
Basic Operations
Indexing
n = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(n[0, 0, 2]) # 3
n[0, 0, 2] = 0
print(n)
n = np.arange(5)
print(n[1:3]) # [1 2]
Reshape
n = np.arange(1, 5)
n2 = np.reshape(n, (2, 2))
print(n2)
Concatenaet
n1 = np.array([[1, 2], [3, 4]])
n2 = np.array([[5, 6], [7, 8]])
print(np.concatenate((n1, n2), axis=0))
Split
n = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
print(np.vsplit(n, 2))
Copy
n1 = np.arange(5)
n2 = n1.copy()
n1[0] = 100
print(n1, n2)
Transpose
n = np.array([[1, 2], [3, 4], [5, 6]])
print(n.T)
Aggregation Operations
n = np.array([1, 2, 3, 4, 5])
print(np.sum(n)) # 15
print(np.max(n)) # 5
print(np.mean(n)) # 3.0
Matrix Operations
n1 = np.array([[1, 2, 3], [2, 3, 4]])
n2 = np.array([[1, 2, 3], [3, 3, 4]])
print(n1 @ n2)
n = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
print(np.linalg.inv(n)) # Inverse matrix
print(np.linalg.det(n)) # Determinant
Sorting
n1 = np.array([1, 2, 8, 6, 5])
print(np.sort(n1)) # [1 2 5 6 8]
File Operations
x = np.arange(0, 5)
y = np.arange(5, 10)
np.save('x.npy', x)
np.savez('xy.npz', xarr=x, yarr=y)
print(np.load('x.npy')) # [0 1 2 3 4]
print(np.load('xy.npz')['yarr']) # [5 6 7 8 9]
n = np.array([[1, 2, 3], [4, 5, 6]])
np.savetxt('n.txt', n, delimiter=',')
print(np.loadtxt('n.txt', delimiter=',')) # [[1. 2. 3.], [4. 5. 6.]]