Tim
Tim

Reputation: 83

How to correct wrong values with Numpy difference in python?

I've been working on my data by Python. My data is imported as a numpy array by using numpy.diff. But it turns out a wrong set of values.

import numpy as np

mydata = np.array([1285, 1328, 1277, 1293,  200, 1284, 1266, 1273, 1252, 1233, 1208, 1166, 1200, 1173,
 1179])

print(np.diff(mydata))

And it shows:

[   43 65485    16 64443  1084 65518     7 65515 65517 65511 65494    34
 65509     6]

which is absolutely wrong!

Who can help me to deal with this problem?

Upvotes: 1

Views: 153

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476729

The type of your array is likely an uint16. Indeed:

>>> my_data =np.array([25,14], dtype=np.uint16)
>>> np.diff(my_data)
array([65525], dtype=uint16)

This happens since unsiged integers can not represent negative numbers, and thus a wraparound is the result.

You can change the type of your array, for example to int32:

>>> np.diff(my_data.astype(np.int32))
array([-11], dtype=int32)

Upvotes: 2

Related Questions