Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace strings in N-d numpy array

i have a 2d array of strings and i want to replace them with other strings that are bigger in length. I tried this

for key, value in UniqueIds.items():
            indices[indices[...] == str(value)] = key

to replace each value with the corresponding key, but each value is 4 bytes and the key is about 10, and the changed value shows only the first 4 letters

like image 744
christk Avatar asked Jul 26 '26 12:07

christk


1 Answers

I think you need to change the dtype of the array, see e.g. here or also here. A 4-character string would be dtype='<U4'. If you'd have an 8-character string, it would be dtype='<U8' and so on.

So if you know the size of your resulting strings, you could specify it explicitly (e.g.dtype='<U10' to hold 10 Unicode characters). If you don't care about memory and copy operations, make it dynamic by using object as dtype:

import numpy as np
s = np.array(['test'], dtype=object)
s[0] = 'testtesttesttest'
# s
# array(['testtesttesttest'], dtype=object)

now .replace() will work:

s[0] = s[0].replace('test', 'notatest')
# s
# array(['notatestnotatestnotatestnotatest'], dtype=object)
like image 153
FObersteiner Avatar answered Jul 28 '26 02:07

FObersteiner



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!