# Demonstrating basic array operations with NumPy
import numpy as np
# Creating two arrays for demonstration
array1 = np.array([1, 2, 3, 4, 5, 6])
array2 = np.array([6, 5, 4, 3, 2, 1])
# Element-wise addition
addition_result = np.add(array1, array2)
print("Addition Result:", addition_result)
# Element-wise multiplication
multiplication_result = np.multiply(array1, array2)
print("Multiplication Result:", multiplication_result)
# Dot product of both arrays
dot_product_result = np.dot(array1, array2)
print("Dot Product Result:", dot_product_result)
# Reshaping array1 to a 2x3 matrix
reshaped_array = np.reshape(array1, (2, -1))
print("Reshaped Array (2x3):\n", reshaped_array)
# Computing the mean of array1
mean_array1 = np.mean(array1)
print("Mean of Array1:", mean_array1)
# Finding the maximum value in array2
max_array2 = np.max(array2)
print("Maximum Value in Array2:", max_array2)NumPy is the array library that most numerical Python code is built on.
Its ndarray holds numbers of one type in a grid with any number of
dimensions, and math on a whole array runs in compiled code, which is much
faster than a loop over a Python list. pandas, SciPy, scikit-learn and
matplotlib all build on it, and people use it directly for data analysis,
simulations and linear algebra. This page is an online NumPy compiler: the
code runs in your browser, so you can try it without installing anything.
Run the example first, then paste any snippet below into a new cell to try it.
np.array() turns a Python list into an array, here two arrays of six
integers. np.add() and np.multiply() work element by element, pairing
the first value of one array with the first of the other, and so on. They
give the same result as array1 + array2 and array1 * array2.
np.dot() adds up those products: 6 + 10 + 12 + 12 + 10 + 6 = 56.
np.reshape(array1, (2, -1)) arranges the six values in two rows, and
-1 tells NumPy to work out the number of columns. np.mean() and
np.max() reduce an array to a single number.
These functions build arrays of a given size. Every array has a shape,
a number of dimensions (ndim) and one dtype shared by all its values:
import numpy as np
print(np.arange(0, 10, 2)) # like range(): start, stop, step
print(np.linspace(0, 1, 5)) # 5 evenly spaced points, end included
print(np.zeros((2, 3))) # 2 rows, 3 columns of 0.0
grid = np.arange(12).reshape(3, 4)
print(grid)
print(grid.shape, grid.ndim, grid.dtype)
Comparing an array with a value gives an array of True and False,
called a mask. Indexing with the mask keeps only the matching values, and
assigning through it changes them in place:
import numpy as np
temps = np.array([18.5, 22.1, 25.3, 19.8, 30.2, 27.6, 16.4])
hot = temps > 25
print(hot) # one True/False per value
print(temps[hot]) # only the values where the mask is True
print(hot.sum(), "hot days") # True counts as 1
print(np.where(temps > 25, "hot", "mild"))
temps[temps < 18] = 18 # set every value below 18 to 18
print(temps)
Functions that reduce an array take an axis: axis=0 works down the
columns and axis=1 across the rows. The data comes from
np.random.default_rng(), and a fixed seed gives the same numbers on
every run:
import numpy as np
rng = np.random.default_rng(seed=42)
scores = rng.integers(50, 101, size=(4, 3)) # 4 students, 3 tests
print(scores)
print(scores.mean(axis=0)) # average of each column (per test)
print(scores.max(axis=1)) # best score of each row (per student)
# Broadcasting: subtract each test's average from its column
print(scores - scores.mean(axis=0))
integers() leaves out the upper bound, so scores run from 50 to 100.
The last line uses broadcasting: NumPy repeats the three column averages
for every row, so no loop is needed.
On two arrays, * multiplies element by element. For a matrix product,
use @. The np.linalg module has the usual linear algebra routines:
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print(A * B) # element by element
print(A @ B) # matrix product, same as np.matmul(A, B)
print(A.T) # transpose
print(np.linalg.inv(A))
# Solve 2x + 3y = 5 and 4x - y = 3
coefficients = np.array([[2, 3], [4, -1]])
print(np.linalg.solve(coefficients, np.array([5, 3])))
The SciPy example solves the same two equations with
scipy.linalg.solve.
int32), because Python runs as 32-bit WebAssembly. A 64-bit desktop
install uses int64. Integer results past about 2.1 billion wrap
around without an error: np.arange(100000).sum() gives 704982704
instead of 4999950000. Pass dtype=np.int64 when numbers get large.a[1:3] is a view of the original array, so changing
the slice changes a too. Call .copy() when you need an independent
array. Indexing with a mask always returns a copy.