Search code examples
pythonarraysnumpystring-operations

Merging strs in a numpy array - what's the most effective way?


Let's say I have an array

arr = np.array([['a ', 'b ', 'c'], ['d ', 'e ', 'f']])

and I want to turn it into

[['a b c'], ['d e f']]

using only vectorized operations. What's the most efficient way of doing it?


Solution

  • Cast your array values to python's object type to infer further string addition with np.sum operation:

    arr = np.sum(arr.astype(object), axis=1, keepdims=True)
    

    [['a b c']
     ['d e f']]