Disable silent conversions in numpy

前端 未结 2 1638
梦如初夏
梦如初夏 2021-01-13 12:36

Is there a way to disable silent conversions in numpy?

import numpy as np
a = np.empty(10, int)
a[2] = 4     # OK
a[3] = 4.9   # Will silently convert to 4,          


        
相关标签:
2条回答
  • 2021-01-13 13:02

    Unfortunately numpy doesn't offer this feature in array creation, you can set if casting is allowed only when you are converting an array (check the documentation for numpy.ndarray.astype).

    You could use that feature, or subclass numpy.ndarray, but also consider using the array module offered by python itself to create a typed array:

    from array import array
    
    a = array('i', [0] * 10)
    a[2] = 4                   # OK
    a[3] = 4.9                 # TypeError: integer argument expected, got float
    
    0 讨论(0)
  • 2021-01-13 13:13

    Just an idea.

    #Python 2.7.3
    >>> def test(value):
    ...     if '.' in str(value):
    ...         return str(value)
    ...     else:
    ...         return value
    ... 
    >>> a[3]=test(4.0)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: invalid literal for long() with base 10: '4.0'
    
    0 讨论(0)
提交回复
热议问题