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')
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With