w3resource

NumPy: Stack 1-D arrays as columns wise


Stack 1D Arrays as Columns

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.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to stack two 1D arrays as columns using np.column_stack and verify the 2D output.
  • Create a function that transforms multiple 1D arrays into a single 2D column-stacked array.
  • Test the column stacking with arrays of varying lengths and ensure proper error handling.
  • Implement a solution using np.newaxis to convert 1D arrays to column vectors before stacking.

Go to:


PREV : Stack Arrays Vertically
NEXT : Stack 1D Arrays as Rows


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.