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...<br>",arr)

Get the datatype −

print("\nArray datatype...<br>",arr.dtype)

Get the dimensions of the Array −

print("\nArray Dimensions...<br>",arr.ndim)

Get the shape of the Array −

print("\nOur Array Shape...<br>",arr.shape)

Get the number of elements of the Array −

print("\nElements in the Array...<br>",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("\nResult (expand tabs)...<br>",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...<br>",seq)

# Get the datatype
print("\nArray datatype...<br>",seq.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...<br>",seq.ndim)

# Get the shape of the Array
print("\nOur Array Shape...<br>",seq.shape)

# Get the number of elements of the Array
print("\nElements in the Array...<br>",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("\nResult...<br>",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: 2022-02-17T11:36:04+05:30

162 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements