NumPy Examples (array, random, arange)
This page was last reviewed on Sep 18, 2023.
Dot Net Perls
NumPy. 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.
An example. To begin using NumPy, please install it from pip (a Python installer). Once installed, you can import "numpy" as "np."
Start Here we create an array with 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.
Here We generate a 1-dimensional array of 5 random 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]]
Arange. 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.
Argument 1 This is the starting value for the range. So with 5, our range starts at the value 5.
Argument 2 The exclusive end of the range—this value is not included in the range. With a value of 6, our range does not include 6.
Argument 3 The step—this is how much each element in the resulting range is incremented. This is the same way Python slices work.
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]
Notes, broadcasting. 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.
Some notes. NumPy is a powerful library. And its support in other libraries like TensorFlow make it a non-optional one (for certain use cases).
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 18, 2023 (edit).
© 2007-2024 Sam Allen.