You can create a NumPy array using various methods provided by the NumPy library. Here are some common ways to create NumPy arrays:
- From a List or Tuple:
import numpy as np
list_data = [1, 2, 3, 4, 5]
numpy_array = np.array(list_data)
- Using NumPy Functions:
import numpy as np
# Create an array of zeros
zeros_array = np.zeros(5)
# Create an array of ones
ones_array = np.ones(3)
# Create an array with a range of values
range_array = np.arange(0, 10, 2) # Start, Stop, Step
# Create an array with evenly spaced values
linspace_array = np.linspace(0, 1, 5) # Start, Stop, Number of points
- Creating Multi-Dimensional Arrays:
import numpy as np
# Create a 2D array
matrix = np.array([[1, 2, 3], [4, 5, 6]])
# Create a 3D array
tensor = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
- Using Special Functions:
import numpy as np
# Create an identity matrix
identity_matrix = np.eye(3)
# Create an array of random values
random_array = np.random.rand(4)
# Create a 2D array of random integers
random_integers = np.random.randint(1, 10, size=(3, 3))
These are just a few examples of how you can create NumPy arrays. NumPy offers a wide range of functions to generate arrays with specific properties, making it highly versatile for different data manipulation and analysis tasks.