Insert Row/Columns, Append Row/Columns, Array Manipulation
np.insert() — insert elements/rows/columns
import numpy as np
a = np.array([10, 20, 30, 40])
b = np.insert(a, 2, 99) # insert 99 at index 2
print(b) # [10 20 99 30 40]
m = np.array([[1, 2], [3, 4]])
row_inserted = np.insert(m, 1, [9, 9], axis=0) # insert a new row at index 1
print(row_inserted)
# [[1 2]
# [9 9]
# [3 4]]
col_inserted = np.insert(m, 1, [8, 8], axis=1) # insert a new column at index 1
print(col_inserted)
# [[1 8 2]
# [3 8 4]]
np.append() — append elements/rows/columns to the end
a = np.array([1, 2, 3])
b = np.append(a, [4, 5])
print(b) # [1 2 3 4 5]
m = np.array([[1, 2], [3, 4]])
new_row = np.append(m, [[5, 6]], axis=0)
print(new_row)
# [[1 2]
# [3 4]
# [5 6]]
new_col = np.append(m, [[7], [8]], axis=1)
print(new_col)
# [[1 2 7]
# [3 4 8]]
np.delete() — remove elements/rows/columns
a = np.array([10, 20, 30, 40])
print(np.delete(a, 1)) # [10 30 40] -- removes index 1
m = np.array([[1, 2], [3, 4], [5, 6]])
print(np.delete(m, 1, axis=0)) # removes row index 1
print(np.delete(m, 0, axis=1)) # removes column index 0
Array Manipulation Operations
a = np.array([[1, 2], [3, 4]])
print(a.T) # transpose -- swap rows and columns
# [[1 3]
# [2 4]]
b = np.array([1, 2, 3])
c = np.array([4, 5, 6])
print(np.concatenate([b, c])) # [1 2 3 4 5 6]
print(np.vstack([b, c])) # stack vertically -> 2 rows
# [[1 2 3]
# [4 5 6]]
print(np.hstack([b, c])) # stack horizontally -> [1 2 3 4 5 6]
print(np.split(np.arange(9), 3)) # split into 3 equal parts
# [array([0,1,2]), array([3,4,5]), array([6,7,8])]
print(np.sort(np.array([5, 2, 8, 1]))) # [1 2 5 8]
print(np.unique(np.array([1, 2, 2, 3, 3, 3]))) # [1 2 3]
Quick reference table
| Function | Purpose |
|---|
np.insert(arr, idx, val, axis) | Insert value(s) at index |
np.append(arr, val, axis) | Append value(s) at the end |
np.delete(arr, idx, axis) | Remove element/row/column |
arr.T | Transpose |
np.concatenate | Join arrays along an axis |
np.vstack / np.hstack | Stack vertically / horizontally |
np.split | Divide an array into sub-arrays |
np.sort / np.unique | Sort / get unique elements |