Issue
Code:
import numpy as np
data = '12345\n54321\n13542\n12354\n53124'
n = data.find('\n')
mat = np.array(list(data.replace('\n','')), dtype=np.uint8).reshape(-1, n)
mat
Out:
array([[1, 2, 3, 4, 5],
[5, 4, 3, 2, 1],
[1, 3, 5, 4, 2],
[1, 2, 3, 5, 4],
[5, 3, 1, 2, 4]], dtype=uint8)
Code:
mat2 = np.full_like(mat, 0)
mat2[0,0] = 9999999
mat2[0,1] = 8888
mat2[0,2] = 77777
Out:
array([[127, 184, 209, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0]], dtype=uint8)
Thus, Python does not set the needed numpy array item value, only a random and tiny value gets saved instead for a wide range of number sizes. How to fix this?
Solution
Sharing this since I did not know for some time what was going on, even though it seems so clear at first sight if you look at a small example like this. In a bigger code, such things can hide for a while.
You need to change the data type from uint8 (--> unsigned int, and 8 Bits is the least you need to choose for an array, that is why I chose it for some small values in the first place) to a data type that can save the larger values. For example:
mat2 = np.full_like(mat, 0).astype('uint32')
mat2[0,2] = 77777
mat2
Out:
array([[ 0, 0, 77777, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0]], dtype=uint32)
Answered By - questionto42
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.