﻿ NumPy: Concatenate element-wise two arrays of string - w3resource

# 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)
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.

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]
```

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