How to Concatenate Strings of a Numpy Array in Python?

Estimated read time 2 min read

To concatenate strings of a NumPy array in Python, you can use the numpy.core.defchararray.add() function. This function allows you to concatenate strings element-wise in a NumPy array. Here’s an example:

import numpy as np

# Example array of strings
arr = np.array(['Hello', 'World', '!', 'Concatenate'])

# Concatenate the strings in the array
concatenated_arr = np.core.defchararray.add(arr, ' ')

# Convert the concatenated array back to a single string
concatenated_string = ' '.join(concatenated_arr)

print(concatenated_string)  # Output: Hello World ! Concatenate

In this example, we have a NumPy array arr containing a series of strings.

To concatenate the strings in the array, we use the np.core.defchararray.add() function. This function takes two arguments: the array of strings to concatenate and the string to concatenate with.

The function performs element-wise concatenation, adding the specified string to each element of the array.

After concatenating the strings in the array, we use the join() method to convert the resulting concatenated array back to a single string. In this case, we use a space ' ' as the separator between the concatenated strings.

The resulting concatenated_string variable contains the concatenated strings as a single string.

Note that np.core.defchararray.add() is specifically designed for string arrays in NumPy. If you have a regular NumPy array of objects and want to concatenate their string representations, you can use a combination of list comprehension and string concatenation instead.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply