NumPy: Stack arrays in sequence vertically
Stack Arrays Vertically
Write a NumPy program to stack arrays vertically.
Pictorial Presentation:
Sample Solution:
Python Code:
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 vertically: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 0 3 6] [ 9 12 15] [18 21 24]]
Explanation:
In the above code -
x = np.arange(9).reshape(3,3): This line 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.
new_array = np.vstack((x, y)): It vertically stacks the two 3x3 arrays x and y, resulting in a new 6x3 array new_array:
Finally, print() function prints the vertically stacked new_array.
For more Practice: Solve these Related Problems:
- Write a NumPy program to vertically stack two arrays using np.vstack and verify the final array dimensions.
- Create a function that merges multiple 2D arrays row-wise and checks that the row order is maintained.
- Test vertical stacking on arrays with inconsistent column counts and handle the exceptions.
- Implement a solution that demonstrates the difference between np.vstack and np.concatenate along axis=0.
Python-Numpy Code Editor:
Previous: Write a NumPy program to stack arrays in sequence horizontally (column wise).Next: Write a NumPy program to stack 1-D arrays as columns wise.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics