w3resource

NumPy: Concatenate two given arrays of shape (2, 2) and (2,1)

NumPy: Array Object Exercise-197 with Solution

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:

Previous: Write a NumPy program to create a 12x12x4 array with random values and extract any array of shape(6,6,3) from the said array.
Next: Write a NumPy program to create a 10x4 array filled with random floating point number values with and set the array values with specified precision.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://198.211.115.131/python-exercises/numpy/python-numpy-exercise-197.php