pythonarraysstringnumpyelementwise-operations

Element-wise string concatenation in numpy


Is this a bug?

import numpy as np
a1=np.array(['a','b'])
a2=np.array(['E','F'])

In [20]: add(a1,a2)
Out[20]: NotImplemented

I am trying to do element-wise string concatenation. I thought Add() was the way to do it in numpy but obviously it is not working as expected.


Solution

  • This can be done using numpy.char.add. Here is an example:

    >>> import numpy as np
    >>> a1 = np.array(['a', 'b'])
    >>> a2 = np.array(['E', 'F'])
    >>> np.char.add(a1, a2)
    array(['aE', 'bF'], 
          dtype='<U2')
    

    (This was previously known as numpy.core.defchararray.add, and that name is still usable, but numpy.char.add is the preferred alias now.)

    There are other useful string operations available for NumPy data types.