numpy array with dtype Decimal?

前端 未结 3 1726
再見小時候
再見小時候 2020-11-29 09:30

Are Decimal dtypes available in numpy?

>>> import decimal, numpy
>>> d = decimal.Decimal(\'1.1\') 
>>> s = [[\'123.123\',\'23\'],[         


        
相关标签:
3条回答
  • 2020-11-29 09:41

    IMPORTANT CAVEAT: THIS IS A BAD ANSWER

    So I answered this question before I really understood the point of it. The answer was accepted, and has some upvotes, but you would probably do best to skip to the next one.

    Original answer:

    It seems that Decimal is available:

    >>> import decimal, numpy
    >>> d = decimal.Decimal('1.1')
    >>> a = numpy.array([d,d,d],dtype=numpy.dtype(decimal.Decimal))
    >>> type(a[1])
    <class 'decimal.Decimal'>
    

    I'm not sure exactly what you are trying to accomplish, your example is more complicated than is necessary for simply creating a decimal numpy array.

    0 讨论(0)
  • 2020-11-29 09:42

    Numpy doesn't recognize decimal.Decimal as a specific type. The closest it can get is the most general dtype, object. So when converting the elements to the desired dtype, the conversion is a no-op.

    >>> ss.dtype
    dtype('object')
    

    Keep in mind that because the elements of the array are Python objects, you won't get much of a speed up using them. For example, if you try to add this to any other array, the others elements will have to be boxed back into python objects and added via the normal Python addition code. You might gain some speed in that the iteration will be in C, but not that much.

    0 讨论(0)
  • 2020-11-29 09:42

    Unfortunately, you have to cast each of your items to Decimal when you create the numpy.array. Something like

    s = [['123.123','23'],['2323.212','123123.21312']]
    decimal_s = [[decimal.Decimal(x) for x in y] for y in s]
    ss = numpy.array(decimal_s)
    
    0 讨论(0)
提交回复
热议问题