изменение dtype массива numpy на что-то нестандартное - PullRequest
0 голосов
/ 06 мая 2020

Как преобразовать массив numpy из str s в массив объектов моего класса? Мой собственный класс наследуется от 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

Есть ли какой-нибудь метод c, который мне нужно реализовать?

1 Ответ

1 голос
/ 06 мая 2020
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)
...