NumPy is a Python library for working with arrays. NumPy arrays are similar to lists, but are more efficient for numerical operations.
Here's an example of how to create a NumPy array:
Python:
import numpy as np
a = np.array([1, 2, 3])
print(a)
In this example, we import the numpy library and use it to create a NumPy array containing the numbers 1, 2, and 3.
You can perform arithmetic operations on NumPy arrays, like addition and multiplication:
Python:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = a + b
d = a * b
print(c)
print(d)
In this example, we create two NumPy arrays a and b and perform element-wise addition and multiplication to create two new arrays c and d.
NumPy arrays also support slicing and indexing, just like lists:
Python:
import numpy as np
a = np.array([1, 2, 3, 4, 5])
print(a[0]) # prints the first element
print(a[-1]) # prints the last element
print(a[1:4]) # prints elements 1, 2, and 3
In this example, we create a NumPy array a and use indexing and slicing to access its elements.
You can create multi-dimensional NumPy arrays by passing nested lists to the np.array() function:
Python:
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a)
print(a[0, 0]) # prints the first element in the first row
print(a[1, 2]) # prints the last element in the second row
In this example, we create a 2-dimensional NumPy array a and use indexing to access its elements.
NumPy also provides many built-in functions for working with arrays, like np.mean() to calculate the mean of an array:
Python:
import numpy as np
a = np.array([1, 2, 3, 4, 5])
print(np.mean(a))
In this example, we calculate the mean of the NumPy array a using the np.mean() function.