Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Numpy char.join() Function



The Numpy char.join() function is used to join elements of an array of strings with a specified separator. This function operates element-wise by combining the characters or substrings within each element of the array into a single string, separated by the provided delimiter.

This function is useful for formatting and concatenating string data in a controlled manner.

Syntax

Following is the syntax of Numpy char.join() function −

numpy.char.join(sep, seq)

Parameters

Following are the parameters of Numpy char.join() function −

  • sep(str or array-like of str): The separator string or an array-like object of separator strings to use for joining.

  • seq(array-like of str or unicode): The input array containing strings to be joined.

Return Value

This function returns an array with the same shape as the input, where each element is a string joined with the specified separator.

Example 1

Following is the basic example of Numpy char.join() function. Here in this example we joined the strings of the array with a specified separator '-' −

import numpy as np

arr = np.array(['abc', 'def', 'ghi'])
joined_arr = np.char.join('-', arr)
print(joined_arr)

Below is the output of the basic example of numpy.char.join() function −

['a-b-c' 'd-e-f' 'g-h-i']

Example 2

The char.join() function allows us to specify different separators for each string in an array by providing flexible string formatting. Here in this example each string in the array is joined as specified in the separators array −

import numpy as np

arr = np.array(['abc', 'def', 'ghi'])
separators = np.array(['-', ':', '*'])
joined_arr = np.char.join(separators, arr)
print(joined_arr)

Here is the output of including newline characters −

['a-b-c' 'd:e:f' 'g*h*i']

Example 3

We can also apply the char.join() function to multi-dimensional arrays for joining characters in each string element with a specified separator. Following is the example of joining elements of a multi-dimensional array −

import numpy as np

arr = np.array([['abc', 'def'], ['ghi', 'jkl']])
joined_arr = np.char.join('-', arr)
print(joined_arr)

Here is the output of limiting the number of joins −

[['a-b-c' 'd-e-f']
 ['g-h-i' 'j-k-l']]
numpy_string_functions.htm
Advertisements