将numpy数组的dtype更改为自定义

时间:2020-05-06 03:56:51

标签: python-3.x numpy enums numpy-ndarray

如何将numpy的{​​{1}}数组转换为类对象的数组?我的自定义类继承自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')

我必须实现一些魔术方法吗?

1 个答案:

答案 0 :(得分: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)