Cannot cast array data from dtype('float64') to dtype('int32') according to the rule 'safe'

前端 未结 2 907
忘掉有多难
忘掉有多难 2021-01-22 07:00

I have a numpy array like

result = np.array([[[289, 354, 331],
                    [291, 206,  66],
                    [242,  70, 256]],

                   [[         


        
2条回答
  •  [愿得一人]
    2021-01-22 07:31

    Explanation of Error:

    This is illustrative of an interesting property of numpy arrays: all elements of a numpy array must be of the same type

    For instance if you have the following array:

    >>> array1 = np.array([[23, 632, 634],[23.5, 67, 123.6]])
    >>> array1
    array([[  23. ,  632. ,  634. ],
       [  23.5,   67. ,  123.6]])
    >>> type(array1[0][0])
    
    

    We notice that even though all the elements in the list [23, 632, 634] were all of the type int (specifically 'numpy.int64'), all of the elements in array1 were converted to floats because of the element 123.6 in the second row (notice the decimal points in the array print out).

    Similarily, if we include even one string anywhere in the array, all the elements of the array are cast to strings:

    >>> array2 = np.array([[23, 632, 'foo'],[23.5, 67, 123.6]])
    >>> type(array2[0][0])
    
    

    Conclusion:

    Your original result array contains elements of type 'numpy.int64', but the result/4 operation returns an array of elements of type 'numpy.float64' (since 82 / 4 = 20.5, etc.). Thus when you try and replace the values in result, it is not 'safe' as you are inadvertently trying to place floats into an array of ints.

提交回复
热议问题