Return a string which is the concatenation of the strings in the sequence in Numpy


To return a string which is the concatenation of the strings in the sequence, use the numpy.char.join() method in Python Numpy. The 1st parameter is the separator array. The 2nd parameter is the sequence array. The function returns an output array of str or unicode, depending on input types

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

Steps

At first, import the required library −

import numpy as np

Create a One-Dimensional array of string −

arr = np.array(['Bella\tCio', 'Tom\tHanks', 'Monry\tHeist\tSeries'])

Displaying our array −

print("Array...
",arr)

Get the datatype −

print("
Array datatype...
",arr.dtype)

Get the dimensions of the Array −

print("
Array Dimensions...
",arr.ndim)

Get the shape of the Array −

print("
Our Array Shape...
",arr.shape)

Get the number of elements of the Array −

print("
Elements in the Array...
",arr.size)

To replace tab characters by a fixed tabsize in a string array, use the numpy.char.expandtabs() method. The "tabsize" parameter is used to replace tabs with tabsize number of spaces. If not given defaults to 8 spaces. We have set the "tabsize" to 10 i.e. 10 spaces −

print("
Result (expand tabs)...
",np.char.expandtabs(arr, tabsize = 10))

Example

import numpy as np

# Create two arrays
sep = np.array([':', '-', '$'])
seq = np.array(['abc', 'def', 'ghi'])

# Displaying our sequence
print("Sequence array...
",seq) # Get the datatype print("
Array datatype...
",seq.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",seq.ndim) # Get the shape of the Array print("
Our Array Shape...
",seq.shape) # Get the number of elements of the Array print("
Elements in the Array...
",seq.size) # To return a string which is the concatenation of the strings in the sequence, use the numpy.char.join() method in Python Numpy # The 1st parameter is the separator array # The 2nd parameter is the sequence array print("
Result...
",np.char.join(sep,seq))

Output

Sequence array...
['abc' 'def' 'ghi']

Array datatype...
<U3

Array Dimensions...
1

Our Array Shape...
(3,)

Elements in the Array...
3

Result...
['a:b:c' 'd-e-f' 'g$h$i']

Updated on: 17-Feb-2022

49 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements