2013-10-21 49 views
3

我需要编写一个函数F,它使用dtype = object的numpy数组,并返回数组的所有元素是浮点数,整数还是字符串。例如:如何快速检查numpy数组的所有元素是否都是浮动的?

F(np.array([1., 2.], dtype=object)) --> float 
F(np.array(['1.', '2.'], dtype=object)) --> string 
F(np.array([1, 2], dtype=object)) --> int 
F(np.array([1, 2.], dtype=object)) --> float 
F(np.array(['hello'], dtype=object)) --> string 

F(np.array([1, 'hello'], dtype=object)) --> ERROR 

任何想法如何有效地做到这一点? (==具有内置功能numpy的)

非常感谢

+1

你想F(np.array([1,2],dtype = object))抛出一个混合int和float的错误原因吗? – bcollins

+0

返回浮点数为F(np.array([1,2],dtype = object))很好。 – Olexiy

回答

2

也许最简单的是通过np.array运行的内容,并检查所生成的类型:

a = np.array([1., 2.], dtype=object) 
b = np.array(['1.', '2.'], dtype=object) 
c = np.array([1, 2], dtype=object) 
d = np.array([1, 2.], dtype=object) 
e = np.array(['hello'], dtype=object) 
f = np.array([1, 'hello'], dtype=object) 

>>> np.array(list(a)).dtype 
dtype('float64') 
>>> np.array(list(b)).dtype 
dtype('S2') 
>>> np.array(list(c)).dtype 
dtype('int32') 
>>> np.array(list(d)).dtype 
dtype('float64') 
>>> np.array(list(e)).dtype 
dtype('S5') 

它没有引发错误在不兼容的情况下,因为这不是numpy的行为:

>>> np.array(list(f)).dtype 
dtype('S5') 
+0

非常感谢!提高错误实际上很简单 - 只要执行np.all(new_array == old_array) – Olexiy

1

不确定这是最有效的对象管理,但如何abou t:

def F(a): 
    unique_types = set([type(i) for i in list(a)]) 
    if len(unique_types) > 1: 
     raise ValueError('data types not consistent') 
    else: 
     return unique_types.pop() 
相关问题