Return element-wise string concatenation for two arrays of string in Numpy

NumpyServer Side ProgrammingProgramming

To return element-wise string concatenation for two arrays of string, use the numpy.char.add() method in Python Numpy.

The numpy.char module provides a set of vectorized string operations for arrays of type numpy.str_ or numpy.bytes_.

The function add() returns the output array of string_ or unicode_, depending on input types of the same shape as x1 and x2. The x1 and x1 are input arrays.

Steps

At first, import the required library −

import numpy as np

Create two One-Dimensional arrays of string

arr1 = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad'])
arr2 = np.array(['Cio', 'Hanks', 'Ceo', 'Hudson', 'Adams', 'Pitt'])

Display the arrays −

print("Array 1...
", arr1)
print("
Array 2...
", arr2)

Get the type of the arrays −

print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)

Get the dimensions of the Arrays −

print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)

Get the shape of the Arrays −

print("
Our Array 1 Shape...
",arr1.shape)
print("
Our Array 2 Shape...
",arr2.shape)

To return element-wise string concatenation for two arrays of string, use the numpy.char.add() method. The arr1 and arr2 are the two input string arrays −

print("
Result...
",np.char.add(arr1,arr2))

Example

import numpy as np

# Create two One-Dimensional arrays of string
arr1 = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad'])
arr2 = np.array(['Cio', 'Hanks', 'Ceo', 'Hudson', 'Adams', 'Pitt'])

# Display the arrays
print("Array 1...
", arr1)
print("
Array 2...
", arr2)

# Get the type of the arrays
print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)

# Get the dimensions of the Arrays
print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)

# Get the shape of the Arrays
print("
Our Array 1 Shape...
",arr1.shape)
print("
Our Array 2 Shape...
",arr2.shape)

# To return element-wise string concatenation for two arrays of string, use the numpy.char.add() method in Python Numpy
# The arr1 and arr2 are the two input string arrays
print("
Result...
",np.char.add(arr1,arr2))

Output

Array 1...
['Bella' 'Tom' 'John' 'Kate' 'Amy' 'Brad']

Array 2...
['Cio' 'Hanks' 'Ceo' 'Hudson' 'Adams' 'Pitt']

Our Array 1 type...
<U5

Our Array 2 type...
<U6

Our Array 1 Dimensions...
1

Our Array 2 Dimensions...
1

Our Array 1 Shape...
(6,)

Our Array 2 Shape...
(6,)

Result...
['BellaCio' 'TomHanks' 'JohnCeo' 'KateHudson' 'AmyAdams' 'BradPitt']
raja
Updated on 17-Feb-2022 10:49:01

Advertisements