w3resource

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:

NumPy: Combine last element with first element of two given ndarray with different shapes.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to concatenate two 1D arrays by merging the last element of the first array with the first element of the second array.
  • Create a function that removes the duplicate boundary element when combining two arrays and returns the merged result.
  • Implement a solution that uses slicing to extract the required portions from both arrays before concatenation.
  • Test the combination on arrays of different lengths to verify that the merged array contains the correct sequence.

Go to:


PREV : Merge three arrays of the same shape.
NEXT : Convert a Python dictionary to a NumPy array.


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.