w3resource

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

NumPy: Array Object Exercise-166 with Solution

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.

Python-Numpy Code Editor:

Previous: Write a NumPy program to merge three given NumPy arrays of same shape.
Next: Write a NumPy program to convert a Python dictionary to a Numpy ndarray.

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://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-166.php