NumPy: Combine last element with first element of two given ndarray with different shapes
Combine the last element of one array with the first of another.
Write a NumPy program to combine last element with first element of two given ndarray with different shapes.
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Creating two lists
array1 = ['PHP', 'JS', 'C++']
array2 = ['Python', 'C#', 'NumPy']
# Printing the original arrays
print("Original arrays:")
print(array1)
print(array2)
# Combining the arrays using np.r_
result = np.r_[array1[:-1], [array1[-1] + array2[0]], array2[1:]]
# Printing the combined result
print("\nAfter Combining:")
print(result)
Sample Output:
Original arrays: ['PHP', 'JS', 'C++'] ['Python', 'C#', 'NumPy'] After Combining: ['PHP' 'JS' 'C++Python' 'C#' 'NumPy']
Explanation:
array1 = ['PHP','JS','C++']
array2 = ['Python','C#', 'NumPy']
The above two statements create two arrays ‘array1’ and ‘array2’ of two 1D arrays containing strings.
result = np.r_[array1[:-1], [array1[-1]+array2[0]], array2[1:]]
In the above code -
- array1[:-1] contains all elements of array1 except the last one, i.e., ['PHP', 'JS'].
- [array1[-1]+array2[0]] creates a new single-element array containing the concatenation of the last element of array1 and the first element of array2, i.e., ['C++Python'].
- array2[1:] contains all elements of array2 except the first one, i.e., ['C#', 'NumPy'].
- np.r_[...] concatenates the three parts (arrays) mentioned above along the first axis (axis=0). The resulting array is ['PHP', 'JS', 'C++Python', 'C#', 'NumPy'].
Pictorial Presentation:
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