w3resource

NumPy: Convert specified inputs to arrays with at least one dimension


Inputs as Arrays with 1+ Dimensions

Write a NumPy program to convert specified inputs into arrays with at least one dimension.

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Defining a scalar value
x = 12.0

# Ensuring that x is at least a 1-dimensional array
print(np.atleast_1d(x))

# Creating a NumPy array with shape (2, 3) using arange and reshape functions
x = np.arange(6.0).reshape(2, 3)

# Ensuring that x is at least a 1-dimensional array
print(np.atleast_1d(x))

# Attempting to convert 1 and [3, 4] into 1-dimensional arrays, which will raise an error
print(np.atleast_1d(1, [3, 4]))

Sample Output:

[ 12.]                                                                 
[[ 0.  1.  2.]                                                         
 [ 3.  4.  5.]]                                                        
[array([1]), array([3, 4])] 

Explanation:

In the above code –

  • ‘x = 12.0’ defines a float variable x with the value 12.0.
  • print(np.atleast_1d(x)): The np.atleast_1d() function takes the input x and converts it into an array with at least one dimension. Since x is a scalar, it is converted into a 1D array with one element. The output is [12.].
  • ‘x = np.arange(6.0).reshape(2, 3)’ creates a 2D array x with shape (2, 3) using the np.arange() and reshape() functions.
  • print(np.atleast_1d(x)): Since x is already a 2D array, the np.atleast_1d() function doesn't change its dimensions
  • print(np.atleast_1d(1, [3, 4])): The np.atleast_1d() function can also take multiple inputs. In this case, it takes a scalar (1) and a list ([3, 4]). Both inputs are converted to 1D arrays, and the output is a tuple containing the 1D arrays: [array([1]), array([3, 4])]

Python-Numpy Code Editor: