Creating arrays is the first step in working with NumPy. Arrays can be created from Python lists or using special functions offered by NumPy.
You can convert a list or tuple into a NumPy array using np.array()
.
import numpy as np
# From a Python list
arr = np.array([10, 20, 30])
print(arr)
Output:
[10 20 30]
# 2D Array (Matrix)
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2d)
Output:
[[1 2 3] [4 5 6]]
NumPy provides several built-in functions to create arrays quickly:
np.zeros()
– Array of all zerosnp.ones()
– Array of all onesnp.full()
– Array filled with a constantnp.eye()
– Identity matrixnp.arange()
– Array with a range of valuesnp.linspace()
– Evenly spaced values over a rangenp.zeros((2, 3)) # 2x3 array of zeros
np.ones((3,)) # 1D array of ones
np.full((2, 2), 7) # 2x2 array with all values 7
np.eye(3) # 3x3 identity matrix
np.arange(1, 10, 2) # [1 3 5 7 9]
np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1. ]
You can specify the data type using the dtype
parameter:
arr = np.array([1, 2, 3], dtype='float32')
print(arr)
NumPy also provides methods to create arrays with random values:
np.random.rand(2, 2) # Random floats in [0, 1)
np.random.randint(1, 10, 5) # Random integers from 1 to 9
numpy.ndarray
, and they are more efficient than Python lists.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!