将一个numpy数组的dtype改为自定义的类型。

问题描述 投票:0回答:1

我如何转换一个 numpy 一系列 str继承到我的类对象的数组中?我的自定义类继承于 Enum.

我有一个关于扑克牌数值的类。

from enum import Enum

from functools import total_ordering
from collections import namedtuple

@total_ordering
class Values(Enum):
    TWO = '2' 
    THREE = '3'
    FOUR = '4'
    FIVE = '5'
    SIX = '6'
    SEVEN = '7'
    EIGHT = '8'
    NINE =  '9'
    TEN = '10'
    JACK = 'j'
    QUEEN = 'q'
    KING = 'k'
    ACE ='a'

    def __lt__(self, other):
        if isinstance(other, type(self)):
            ov = np.array(['2', '3', '4', '5', '6', '7', '8', '9', '10', 'j', 'q', 'k', 'a'])    
            where_first = np.where(self.value == ov)[0][0]
            greater_than_first = ov[(where_first+1):]

            if other.value in greater_than_first:
                return True
            else:
                return False

        return NotImplemented

当我尝试 np.array(['a','j','q']).astype('Values') 我得到

Traceback (most recent call last):

  File "<ipython-input-79-7555e5ef968e>", line 1, in <module>
    np.array(['a','j','q']).astype('Values')

TypeError: data type "Values" not understood

有没有什么神奇的方法需要我去实现?

python-3.x numpy enums numpy-ndarray
1个回答
1
投票
In [32]: Values('a')                                                                                   
Out[32]: <Values.ACE: 'a'>
In [33]: np.array(['a','j','q']).astype(Values)                                                        
Out[33]: array(['a', 'j', 'q'], dtype=object)
In [34]: np.array(['a','j','q']).astype('Values')                                                      
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-34-7555e5ef968e> in <module>
----> 1 np.array(['a','j','q']).astype('Values')

TypeError: data type "Values" not understood
In [35]: arr = np.array([Values(i) for i in 'ajq'])                                                    
In [36]: arr                                                                                           
Out[36]: 
array([<Values.ACE: 'a'>, <Values.JACK: 'j'>, <Values.QUEEN: 'q'>],
      dtype=object)
© www.soinside.com 2019 - 2024. All rights reserved.