Creating NumPy Arrays
NumPy arrays are the foundation of numerical computing in Python. They offer fast operations and efficient memory usage compared to Python lists.
Installing NumPy
Before creating NumPy arrays, ensure that NumPy is installed. You can install it using pip:
pip install numpy
Creating Arrays Using numpy.array()
NumPy arrays can be created from Python lists using the numpy.array()
function.
import numpy as np # Creating a 1D array arr1 = np.array([1, 2, 3, 4, 5]) print(arr1) # Creating a 2D array arr2 = np.array([[1, 2, 3], [4, 5, 6]]) print(arr2)
Output:
[1 2 3 4 5] [[1 2 3] [4 5 6]]
Creating Arrays with Predefined Functions
NumPy provides several functions to create arrays with predefined values:
# Creating an array of zeros zeros = np.zeros((2, 3)) print(zeros) # Creating an array of ones ones = np.ones((3, 2)) print(ones) # Creating an array with a range of values arange = np.arange(0, 10, 2) print(arange)
Output:
[[0. 0. 0.] [0. 0. 0.]] [[1. 1.] [1. 1.] [1. 1.]] [0 2 4 6 8]
Creating Random Arrays
NumPy also provides functions to generate random arrays:
# Creating a random array with values between 0 and 1 rand_arr = np.random.rand(2, 3) print(rand_arr) # Creating a random integer array rand_int_arr = np.random.randint(1, 10, (2, 3)) print(rand_int_arr)
Output:
[[0.5488135 0.71518937 0.60276338] [0.54488318 0.4236548 0.64589411]] [[3 7 1] [8 5 2]]
Conclusion
NumPy arrays can be created in multiple ways, including converting lists, using built-in functions, or generating random numbers. Understanding these methods is essential for effective numerical computing.