NumPy: Stack 1-D arrays as row wise
NumPy: Array Object Exercise-130 with Solution
Stack 1D Arrays as Rows
Write a NumPy program to stack 1-D arrays row 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 rows using np.row_stack()
new_array = np.row_stack((x, y))
# Printing a message indicating the stacking of 1-D arrays as rows and displaying the resulting new array
print("\nStack 1-D arrays as rows wise:")
print(new_array)
Sample Output:
Original arrays: Array-1 [1 2 3] Array-2 [2 3 4] Stack 1-D arrays as rows wise: [[1 2 3] [2 3 4]]
Explanation:
In the above code -
- x = np.array((1,2,3)): It creates a 1-dimensional NumPy array x with the elements 1, 2, and 3.
- y = np.array((2,3,4)): It creates another 1-dimensional NumPy array y with the elements 2, 3, and 4.
- new_array = np.row_stack((x, y)): It stacks the two 1-dimensional arrays x and y row-wise to form a new 2-dimensional array new_array.
- Finally print() function prints the new_array.
Pictorial Presentation:
Python-Numpy Code Editor:
Previous: Write a NumPy program to stack 1-D arrays as columns wise.
Next: Write a NumPy program to split an given array into multiple sub-arrays vertically (row-wise).
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-130.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics