NumPy: Concatenate two given arrays of shape (2, 2) and (2,1)
Concatenate arrays with different shapes.
Write a NumPy program to create to concatenate two given arrays of shape (2, 2) and (2,1).
Sample Solution:
Python Code:
# Importing NumPy library
import numpy as np
# Creating two NumPy arrays
nums1 = np.array([[4.5, 3.5],
[5.1, 2.3]])
nums2 = np.array([[1],
[2]])
# Displaying the original arrays
print("Original arrays:")
print(nums1)
print(nums2)
# Concatenating the two arrays along axis 1 (column-wise concatenation)
concatenated_array = np.concatenate((nums1, nums2), axis=1)
# Displaying the concatenated array
print("\nConcatenating the said two arrays:")
print(concatenated_array)
Sample Output:
Original arrays: [[4.5 3.5] [5.1 2.3]] [[1] [2]] Concatenating the said two arrays: [[4.5 3.5 1. ] [5.1 2.3 2. ]]
Explanation:
nums1 = np.array([[4.5, 3.5], [5.1, 2.3]]): This line creates a 2x2 NumPy array.
nums2 = np.array([[1],[2]]): This line creates a 2x1 NumPy array.
print(np.concatenate((nums1, nums2), axis=1)): Here the np.concatenate() function is used to concatenate these arrays. The axis=1 parameter specifies that the concatenation should be performed along the second dimension (axis 1), which is the columns. Finally print() function prints the resulting 2x3 array.
Python-Numpy Code Editor:
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