Loading

numpy踩坑记录

  1. 当向一个numpy int型array 减去 一个float数的时候,不会自动类型更新。
    示例:
subtracting float number

In [1]: a = np.array([[1,2],[2,3],[3,4]])

In [2]: a[:,1] - 0.5
Out[2]: array([ 1.5,  2.5,  3.5])   # <-- seems to be ok

In [3]: a[:,1] = a[:,1] - 0.5       # <-- auto-update the array column

In [4]: a
Out[4]:
array([[1, 1],
       [2, 2],
       [3, 3]])                     # <-- same result a[:,1] = a[:,1] - 1

原因:
NumPy arrays have a fixed datatype (dtype) which is inferred from the initialization data if you don't specify it yourself. It won't change unless you tell it to, so in your first case:
a[:,1] - 0.5

you're OK because you create a new array with a new, float dtype inferred as necessary from the calculation(the original a is not changed.) In your second, you are actually trying to change the values in a, which is an integer array, so the result of the calculation is cast to an integer: int(2-0.5) is 1, for example.

To do float arithmetic on your array, upcast it to float explicitly with astype: (解决方案:.astype('float')

In [32]: a.astype('float') - 0.5
Out[32]: 
array([[ 0.5,  1.5],
       [ 1.5,  2.5],
       [ 2.5,  3.5]])
posted @ 2021-09-24 21:24  摇头晃脑学知识  阅读(46)  评论(0编辑  收藏  举报