1. Importing NumPy
To use NumPy, write import numpy as np at the beginning of your program. np is a conventionally used alias.
import numpy as np2. Creating NumPy Arrays
The core of NumPy is the ndarray (n-dimensional array). You can create arrays in various ways.
From Lists:
arr = np.array([1, 2, 3, 4, 5]) # 1D array
print(arr) # Output: [1 2 3 4 5]
arr2d = np.array([[1, 2, 3], [4, 5, 6]]) # 2D array
print(arr2d)
# Output:
# [[1 2 3]
# [4 5 6]]
zeros, ones, empty:
zeros_arr = np.zeros((2, 3)) # Array of all zeros with shape (2, 3)
print(zeros_arr)
# Output:
# [[0. 0. 0.]
# [0. 0. 0.]]
ones_arr = np.ones((3, 2)) # Array of all ones with shape (3, 2)
print(ones_arr)
# Output:
# [[1. 1.]
# [1. 1.]
# [1. 1.]]
empty_arr = np.empty((2, 2)) # Uninitialized array with shape (2, 2) (contents are unpredictable)
print(empty_arr)
arange, linspace
arange_arr = np.arange(10) # Integer array from 0 to 9
print(arange_arr) # Output: [0 1 2 3 4 5 6 7 8 9]
linspace_arr = np.linspace(0, 1, 5) # 5 evenly spaced numbers between 0 and 1
print(linspace_arr) # Output: [0. 0.25 0.5 0.75 1. ]
random
rand_arr = np.random.rand(3, 2) # Array of random numbers between 0 and 1 with shape (3, 2)
print(rand_arr)
randint_arr = np.random.randint(0, 10, (2, 3)) # Array of random integers between 0 and 9 with shape (2, 3)
print(randint_arr)
3. NumPy Array Attributes
NumPy arrays have various attributes:
- shape: Returns the shape of the array (number of elements in each dimension) as a tuple.
- dtype: Returns the data type of the array.
- ndim: Returns the number of dimensions of the array.
- size: Returns the total number of elements in the array.
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # Output: (2, 3)
print(arr.dtype) # Output: int64 (may vary depending on your environment)
print(arr.ndim) # Output: 2
print(arr.size) # Output: 6
4. NumPy Array Operations
NumPy arrays support various operations.
Accessing Elements:
arr = np.array([1, 2, 3, 4, 5])
print(arr[0]) # Output: 1 (first element)
print(arr[-1]) # Output: 5 (last element)
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2d[0, 1]) # Output: 2 (element at row 0, column 1)
Slicing:
arr = np.array([1, 2, 3, 4, 5])
print(arr[1:3]) # Output: [2 3] (elements from index 1 to 2)
print(arr[:3]) # Output: [1 2 3] (first 3 elements)
print(arr[2:]) # Output: [3 4 5] (elements from index 2 onwards)
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2d[:1, :2]) # Output: [[1 2]] (first row, first 2 columns)
Broadcasting:
arr = np.array([1, 2, 3])
print(arr + 5) # Output: [6 7 8] (adds 5 to each element of the array)
reshape: Changes the shape of the array.
arr = np.arange(6)
print(arr.reshape((2, 3))) # Output: [[0 1 2] [3 4 5]] (reshapes to a 2x3 array)
concatenate: Joins arrays together.
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
print(np.concatenate((arr1, arr2))) # Output: [1 2 3 4 5 6]
vstack, hstack: Joins arrays vertically and horizontally.
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
print(np.vstack((arr1, arr2)))
# Output: [[1 2] [3 4] [5 6] [7 8]] (joins vertically)
print(np.hstack((arr1, arr2)))
# Output: [[1 2 5 6] [3 4 7 8]] (joins horizontally)
5. NumPy Functions
NumPy provides various functions useful for numerical computation.
sum, mean, std: Calculates the sum, average, and standard deviation.
arr = np.array([1, 2, 3, 4, 5])
print(np.sum(arr)) # Output: 15
print(np.mean(arr)) # Output: 3.0
print(np.std(arr)) # Output: 1.4142135623730951
max, min: Calculates the maximum and minimum values.
arr = np.array([1, 2, 3, 4, 5])
print(np.max(arr)) # Output: 5
print(np.min(arr)) # Output: 1
exp, log: Calculates exponential and logarithmic functions.
arr = np.array([1, 2, 3])
print(np.exp(arr)) # Output: [ 2.71828183 7.3890561 20.08553692]
print(np.log(arr)) # Output: [0. 0.69314718 1.09861229]
sin, cos: Calculates trigonometric functions.
arr = np.array([0, np.pi/2, np.pi])
print(np.sin(arr)) # Output: [0. 1. 0.]
print(np.cos(arr)) # Output: [1. 0. -1.]
6. Advanced NumPy Usage
Matrix Calculation: NumPy can efficiently perform matrix calculations.
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
print(np.dot(matrix1, matrix2))
# Output: [[19 22] [43 50]] (matrix product)
Linear Algebra: NumPy provides various linear algebra functions.
matrix = np.array([[1, 2], [3, 4]])
print(np.linalg.inv(matrix)) # Output: [[-2. 1. ] [ 1.5 -0.5]] (inverse matrix)
print(np.linalg.eigvals(matrix)) # Output: [-0.37228132 5.37228132]