3

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

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Technically 'U10' is 10 unicode characters, or 40 bytes as numpy` implements it (itemsize).
@hpaulj thanks for the clarification! Made an edit to reflect that.
0

the problem was that i converted the initial array of ints to an array of strings like this :

indices = np.char.mod('%d', indices)

When i changed the line above with this one:

indices = indices.astype(str)

everything worked as expected.

2 Comments

ok ;-) still... check the dtype of indices - the resulting dtype will depend on what you had before calling .astype(str). If it e.g. was int32, dtype is something like <U11 - so you're still limited what you can put in.
Alright, thanks and I hope it will be helpful anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.