Home > OS >  what is the principle in dtype convertion in numpy?
what is the principle in dtype convertion in numpy?

Time:09-26

Recentell I found a phononmen, let there is a int array named data whose value is

[[1,2,3],
[4,5,6]]

And I want to subtract a float and I wrote like below

data[0] = data[0] - 0.5

In my mind, data should be

[[0.5, 1.5, 2.5],
[  4,   5,   6]]

Actually, data doesn't change. And I use another way => data[0] -= 0.5, and there is a dtype error.

So, I use astype and make it work, but what confuse me is why data[0] = data[0] - 0.5 doesn't cause error? What is the difference between data[0] = data[0] - 0.5 and data[0] -= 0.5? I found [1] said it is equivalent.

CodePudding user response:

Actually, data was changed, you just ended up replacing some values with the same values. The expression data[0] - 0.5 creates a new array allowed to have a new dtype, in this case a float dtype array [0.5, 1.5, 2.5]. However, data is an integer dtype array, and it can't change its dtype, even if you try to assign the float array [0.5, 1.5, 2.5] to a part of it data[0]. It ends up rounding to [1, 2, 3], which happen to be the same values. Try data[0] = data[0] - 1.5, and you'll see a difference.

Second, the source that told you x = x y is equivalent to x = y is wrong in Python. x = x y does x.__add__(y) addition then = assignment. x = y is implemented by x.__iadd__(y), a completely separate method. In most cases though, __add__ and __iadd__ will do very similar things.

Your case is further complicated by the indexing data[0] -= 0.5 so data.__setitem__(0, temp) will be called after temp = data[0].__isub__(0.5).

  • Related