Python has serious limitations in numeric processing. External libraries like NumPy can improve performance—support for GPU acceleration is even possible.
With methods like np.array
, we create arrays of numbers (of various types) in NumPy. Libraries like TensorFlow use NumPy. It is well-supported.
To begin using NumPy, please install it from pip (a Python installer). Once installed, you can import "numpy" as "np."
np.array
. A Python List
is passed to the method. We then multiply the array by 2.import numpy as np # Create an array of 3 elements. array_one = np.array([5, 10, 15]) print(array_one) # An array can be multiplied by an int. # ... This is an array broadcasting example. array_two = array_one * 2 print(array_two)[ 5 10 15] [10 20 30]
Random
With NumPy we can generate an array of random values with a method call. We specify the size as an argument to random.normal
.
float
values. Some of the numbers are negative.import numpy as np # Create a 1-dimensional array of 5 random values. random_values = np.random.normal(size=[1, 5]) print(random_values)[[ 0.49786323 0.81794554 -0.63191935 0.25130401 0.80529426]]
With NumPy we can get an array based on ranges. The arange method receives 1, 2 or 3 arguments. This works similar to the slice syntax in Python itself.
import numpy as np # Get values using arange method. # ... This is an exclusive bound. values = np.arange(5) print(values) # Two arguments can be used. # ... The second argument is an exclusive bound. values = np.arange(3, 6) print(values) # A step can be used. values = np.arange(0, 5, 2) print(values)[0 1 2 3 4] [3 4 5] [0 2 4]
A powerful feature of NumPy is broadcasting. This allows you to multiply or add two arrays together, and have the elements themselves affected by their positions.
NumPy is a powerful library. And its support in other libraries like TensorFlow make it a non-optional one (for certain use cases).