Concatenate multiple numpy string arrays with a space delimiter

Viewed 2342

Is there a way to generalize Element-wise string concatenation in numpy to n > 2 cases, and also perform the join with a space " " delimiter. The np.char.add function only works for 2 arrays, and there's no option to add a delimiter.

import numpy as np

strings1 = np.array(["a", "b", "c"], dtype=np.str)
strings2 = np.array(["d", "e", "f"], dtype=np.str)
strings3 = np.array(["g", "h", "i"], dtype=np.str)

# Concatenate several string dtype arrays with a space delimiter
# I.e. something like strings1 + " " + strings2 + " " + strings3
# Code??

Desired:

array(['a d g', 'b e h', 'c f i'], dtype='<U5')
3 Answers

Try np.apply_along_axis

arr_list = [strings1, strings2, strings3]
arr_out = np.apply_along_axis(' '.join, 0, arr_list)

In [35]: arr_out
Out[35]: array(['a d g', 'b e h', 'c f i'], dtype='<U5')

You could use a for loop to help you achieve this:

import numpy as np

strings1 = np.array(["a", "b", "c"], dtype=np.str)
strings2 = np.array(["d", "e", "f"], dtype=np.str)
strings3 = np.array(["g", "h", "i"], dtype=np.str)

Create a list of your strings:

strings=[strings1, strings2, strings3]

Create an empty list:

list_for_new_array=[]

For loop to iterate through each array in strings, and create a list of strings containing array items separated by a space:

for string in strings:
    i=""
    for item in string:
        i+=item+" "
    list_for_new_array.append(i)

Create new array with list created in for loop:

new_array= np.array(list_for_array, dtype='<U5')

Try this:

strings = [strings1,strings2,strings3]
np.array([ ' '.join([' '.join(x[i].tolist()) for x in strings ]) for i in range(len(strings)) ],dtype='<U5' )
Related