w3resource

NumPy: Convert 1-D arrays as columns into a 2-D array

NumPy: Array Object Exercise-59 with Solution

Write a NumPy program to convert 1-D arrays as columns into a 2-D array.
Sample array: (10,20,30), (40,50,60)

Pictorial Presentation:

Python NumPy: Convert 1-D arrays as columns into a 2-D array

Sample Solution:

Python Code:

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

# Creating NumPy arrays 'a' and 'b'
a = np.array((10, 20, 30))
b = np.array((40, 50, 60))

# Stacking arrays 'a' and 'b' as columns using np.column_stack
c = np.column_stack((a, b))

# Printing the resulting array 'c'
print(c) 

Sample Output:

[[10 40]                                                               
 [20 50]                                                               
 [30 60]] 

Explanation:

‘a = np.array((10,20,30))’ creates a 1D array a with shape (3,).

‘b = np.array((40,50,60))’ creates another 1D array b with shape (3,).

c = np.column_stack((a, b)): The np.column_stack() function is used to stack the two arrays ‘a’ and ‘b’ as columns in a new 2D array. The resulting array ‘c’ has the shape (3, 2), where the first column contains the elements of ‘a’ and the second column contains the elements of ‘b’.

Python-Numpy Code Editor:

Previous: Write a NumPy program to concatenate two 2-dimensional arrays.
Next: Write a NumPy program to convert (in sequence depth wise (along third axis)) two 1-D arrays into a 2-D array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-59.php