Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate multiple numpy string arrays with a space delimiter

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')
like image 349
weiji14 Avatar asked Oct 19 '25 05:10

weiji14


1 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')
like image 192
Andy L. Avatar answered Oct 21 '25 20:10

Andy L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!