This function allows you to convert input values into an array of at least one dimension.
Let us explore how this function works.
Function Syntax
The function syntax is expressed as shown:
1 | numpy.atleast_1d(*arys) |
Parameters
The function accepts the following parameters:
- array1, array2, array3… – refers to one or more input arrays or array_like objects.
Return Value
The function returns an array or a list of arrays, each with a dimension greater than or equal to 1.
If the input is a scalar value, the function converts it into a one-dimensional array while N-dimensional inputs are conserved.
Example #1
The example below shows how to use the atleast_1d function to convert a scalar value into a one-dimensional array.
1 2 3 4 | # import numpy import numpy as np print(f"array: {np.atleast_1d(10)}") print(f"shape: {np.atleast_1d(10).shape}") |
In the code above, we pass a scalar value to the atleast_1d function, which returns a 1D array as shown:
1 2 | array: [10] shape: (1,) |
Example #2
The example below demonstrates how the function operates on a 2-dimensional array.
1 2 | arr = np.array([[1,2,3], [4,5,6]]) print(np.atleast_1d(arr)) |
The function does not alter the input value as it contains at least one dimension. This means that the input value is preserved.
Example #3
You can also check if the input value is at least one dimension, as shown in the example code below:
1 2 | arr = np.array([[1,2,3], [4,5,6]]) print(np.atleast_1d(arr) is arr) |
Here, we test if the input array is at least 1D. The code above should return:
1 | True |
Closing
This article taught us how to convert an input value into at least one dimension using the np.atleast_1d() function.
Thanks for reading!!