w3resource

NumPy: Stack arrays in sequence horizontally

NumPy: Array Object Exercise-127 with Solution

Write a NumPy program to stack arrays horizontally (column wise).

Pictorial Presentation:

NumPy: Stack arrays in sequence horizontally

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 3x3 NumPy array 'x' with elements from 0 to 8 using np.arange() and reshaping it
x = np.arange(9).reshape(3, 3)

# Creating another 3x3 NumPy array 'y' by multiplying each element of 'x' by 3
y = x * 3

# Printing a message for Array-1 and displaying the original 3x3 array 'x'
print("Array-1")
print(x)

# Printing a message for Array-2 and displaying the modified 3x3 array 'y' (each element multiplied by 3)
print("Array-2")
print(y)

# Stacking Array-1 'x' and Array-2 'y' horizontally using np.hstack()
new_array = np.hstack((x, y))

# Printing a message indicating the horizontal stacking of arrays and displaying the new horizontally stacked array
print("\nStack arrays in sequence horizontally:")
print(new_array) 

Sample Output:

Original arrays:
Array-1
[[0 1 2]
 [3 4 5]
 [6 7 8]]
Array-2
[[ 0  3  6]
 [ 9 12 15]
 [18 21 24]]

Stack arrays in sequence horizontally:
[[ 0  1  2  0  3  6]
 [ 3  4  5  9 12 15]
 [ 6  7  8 18 21 24]]

Explanation:

x = np.arange(9).reshape(3,3): It creates an array with values from 0 to 8 (9 values) using np.arange(9), and then reshapes it into a 3x3 array using reshape(3,3).

y = x*3: It performs element-wise multiplication of the x array by 3, resulting in a new 3x3 array y.

new_array = np.hstack((x, y)): This line horizontally stacks the two 3x3 arrays x and y, resulting in a new 3x6 array new_array.

Finally, print() function prints the horizontally stacked new_array.

Python-Numpy Code Editor:

Previous: Write a NumPy program to rearrange the dimensions of a given array.
Next: Write a NumPy program to stack arrays in sequence vertically.

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.