NumPy: Concatenate element-wise two arrays of string
NumPy String: Exercise-1 with Solution
Write a NumPy program to concatenate element-wise two arrays of string.
Sample Solution:-
Python Code:
import numpy as np
x1 = np.array(['Python', 'PHP'], dtype=np.str)
x2 = np.array([' Java', ' C++'], dtype=np.str)
print("Array1:")
print(x1)
print("Array2:")
print(x2)
new_array = np.char.add(x1, x2)
print("new array:")
print(new_array)
Sample Input:
(['Python', 'PHP'], dtype=np.str) ([' Java', ' C++'], dtype=np.str)
Sample Output:
Array1: ['Python' 'PHP'] Array2: [' Java' ' C++'] new array: ['Python Java' 'PHP C++']
Explanation:
In the above code –
x1 = np.array(['Python', 'PHP'], dtype=np.str): Create a NumPy array x1 containing two strings 'Python' and 'PHP' with data type np.str.
x2 = np.array([' Java', ' C++'], dtype=np.str): Create another NumPy array x2 containing two strings ' Java' and ' C++' with data type np.str.
new_array = np.char.add(x1, x2): Use the np.char.add function to concatenate corresponding elements of x1 and x2 along the first axis, and return a new NumPy array with the concatenated strings. The resulting array is assigned to the variable new_array.
Pictorial Presentation:
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: NumPy String Exercises Home.
Next: Write a NumPy program to repeat all the elements three times of a given array of string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Print Imported Modules:
import sys imported_modules = [m.__name__ for m in sys.modules.values() if m]
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook