简体   繁体   中英

numpy array division turns all elements to zeros

I am trying to divide each element in each row of a matrix by its index, I've created a matching row and filled it from 1 to 1000, however when I do the following:

d = data[0]/np.arange(1,1001)

data[0] = data[0] / np.arange(1,1001)

printing d gives the right caculation:

[1.         0.5        0.33333333 0.25       0.2        0.33333333
 0.28571429 0.25       0.22222222 0.2        0.18181818 0.16666667
 0.23076923 0.21428571 0.2        0.25       0.29411765 0.33333333
 0.31578947 0.35       0.38095238 0.40909091 0.39130435 0.375
 0.4        0.42307692 0.40740741 0.42857143 0.4137931  0.43333333
]

while printing data[0] prints a row of zeros:

[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ]

As you said data[0] is an array of int, so the result of the division is again cast to int, hence you get all 0.

While d is not an array of ints, so the result of the division is cast to float.

data = np.ones((2,1000)).astype(np.int8)
d = data[0]/np.arange(1,1001)
data[0] = data[0] / np.arange(1,1001)

This sample example will lead the same result:

  • data[0] will be an array of zeros (except the element at index 0 that will be a 1)

  • while d will be an array of the float results of the division.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM