If you haven't installed NumPy yet, you can do so using pip:
%pip install numpy
Importing NumPy
To get started with NumPy, you need to import it in your Python script:
import numpy as np
Creating Arrays
NumPy arrays are created with the np.array()
function. You can pass any sequence-like object into this function, and it will be converted into an ndarray (N-dimensional array).
# Create a 1D array
arr1 = np.array([1, 2, 3, 4, 5])
print(arr1)
# Create a 2D array (matrix)
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2)
Array Attributes
Some basic attributes of an ndarray object are:
ndim
: the number of dimensionsshape
: the size of each dimensionsize
: the total number of elementsdtype
: the data type of the elementsarr2 = np.array([[1, 2, 3], [4, 5, 6]])
print("Dimensions:", arr2.ndim) # 2 (Row and Col)
print("Shape:", arr2.shape) # (2, 3),
print("Size:", arr2.size) # 6=2*3
print("Data type:", arr2.dtype) # int64
Basic Operations
NumPy arrays support element-wise operations, which can be performed directly with operators like +, -, *, /.
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Element-wise addition
print(a + b)
# Element-wise multiplication
print(a * b)
Broadcasting