w3resource

NumPy: Stack 1-D arrays as columns wise

NumPy: Array Object Exercise-129 with Solution

Write a NumPy program to stack 1-D arrays columns wise.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Printing a message indicating the original arrays will be displayed
print("\nOriginal arrays:")

# Creating a NumPy array 'x' with elements 1, 2, and 3
x = np.array((1, 2, 3))

# Creating another NumPy array 'y' with elements 2, 3, and 4
y = np.array((2, 3, 4))

# Printing a message for Array-1 and displaying the contents of array 'x'
print("Array-1")
print(x)

# Printing a message for Array-2 and displaying the contents of array 'y'
print("Array-2")
print(y)

# Stacking Array-1 'x' and Array-2 'y' as columns using np.column_stack()
new_array = np.column_stack((x, y))

# Printing a message indicating the stacking of 1-D arrays as columns and displaying the resulting new array
print("\nStack 1-D arrays as columns wise:")
print(new_array) 

Sample Output:

Original arrays:
Array-1
[1 2 3]
Array-2
[2 3 4]

Stack 1-D arrays as columns wise:
[[1 2]
 [2 3]
 [3 4]]

Explanation:

In the above code –

x = np.array((1,2,3)): This line creates a 1-dimensional NumPy array ‘x’ with the elements 1, 2, and 3.

y = np.array((2,3,4)): This line creates another 1-dimensional NumPy array ‘y’ with the elements 2, 3, and 4.

new_array = np.column_stack((x, y)): It stacks the two 1-dimensional arrays x and y column-wise to form a new 2-dimensional array new_array.

Finally print() function prints the new_array.

Pictorial Presentation:

Python NumPy: Stack 1-D arrays as columns wise.

Python-Numpy Code Editor:

Previous: Write a NumPy program to stack arrays in sequence vertically.
Next: Write a NumPy program to stack 1-D arrays as row wise.

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://w3resource.com/python-exercises/numpy/python-numpy-exercise-129.php