NumPy is a popular library for working with arrays and numerical computing in Python. Here are some basic operations you can perform with NumPy arrays:
import numpy as np# Create a 2D arraya = np.array([[1, 2, 3], [4, 5, 6]])# Access elements of the arrayprint(a[0, 0]) # 1print(a[1, 2]) # 6# Create an array of zerosb = np.zeros((2, 3))print(b)# Create an array of onesc = np.ones((2, 3))print(c)# Create a diagonal matrixd = np.diag([1, 2, 3])print(d)# Reshape an arraye = np.arange(6).reshape((2, 3))print(e)# Transpose an arrayf = e.Tprint(f)# Perform element-wise operationsg = np.array([1, 2, 3])h = np.array([4, 5, 6])i = g + hj = g * hprint(i)print(j)# Compute dot productk = np.dot(g, h)print(k)# Compute sum and mean of an arrayl = np.array([[1, 2], [3, 4]])sum_l = np.sum(l)mean_l = np.mean(l)print(sum_l)print(mean_l) |
In this example, we first create a 2D array a with 2 rows and 3 columns. We can access elements of the array using the indexing syntax a[i, j].
We can create arrays of zeros or ones using the zeros and ones functions, respectively. We can create a diagonal matrix using the diag function.
We can reshape an array using the reshape method. We can transpose an array using the T attribute.
We can perform element-wise operations on arrays using standard arithmetic operators such as +, -, *, and /. We can also compute the dot product of two arrays using the dot function.
We can compute the sum and mean of an array using the sum and mean functions, respectively.