This translate
is a string operation. np.char
has a bunch of functions that apply such methods to all elements of a string dtype array:
In [7]: s = "abcdef"
In [8]: arr = np.array([[s,s,s],[s,s,s]])
In [9]: arr
Out[9]:
array([['abcdef', 'abcdef', 'abcdef'],
['abcdef', 'abcdef', 'abcdef']], dtype='<U6')
In [10]: np.char.translate(arr, str.maketrans("abc", "xyz"))
Out[10]:
array([['xyzdef', 'xyzdef', 'xyzdef'],
['xyzdef', 'xyzdef', 'xyzdef']], dtype='<U6')
However, because it calls string methods, it is not particularly fast. Past tests have shown the functions to be about the same speed as explicit loops.
If there were a limited number of such replacements, you could use one of the mapping methods in the proposed duplicate. But if you want to full power of str.translate
, this, or some iteration, is the best you can do. numpy
does not implement string operations in compiled code.
frompyfunc
is a good way of applying a function to all elements of an array. It tends to be modestly faster than more explicit loops:
In [11]: np.frompyfunc(lambda s: s.translate(str.maketrans("abc", "xyz")),1,1)(arr)
Out[11]:
array([['xyzdef', 'xyzdef', 'xyzdef'],
['xyzdef', 'xyzdef', 'xyzdef']], dtype=object)
In [12]: _.astype('U6')
Out[12]:
array([['xyzdef', 'xyzdef', 'xyzdef'],
['xyzdef', 'xyzdef', 'xyzdef']], dtype='<U6')