How do I check that a python value is an instance of a numpy dtype?

时间:2017-06-12 16:59:51

标签: python python-2.7 numpy isinstance

How do I check that a given value can be stored in a numpy array?

E.g.:

import numpy as np
np.array(["a","b"])
==> array(['a', 'b'], dtype='|S1')
np.array(["a","b"]) == 1
> __main__:1: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
==> False
np.array(["a","b"]) == "a"
==> array([ True, False], dtype=bool)

I want a function np_isinstance which would do this:

np_isinstance("a", np.array(["a","b"]).dtype)
==> True
np_isinstance(1, np.array(["a","b"]).dtype)
==> False
np_isinstance("a", np.array([1,2,3]).dtype)
==> False
np_isinstance(1, np.array([1,2,3]).dtype)
==> True

So far I managed to come up with

def np_isinstance(o,dt):
    return np.issubdtype(np.array([o]).dtype, dt)

but this seems wrong because it allocates an array on each invocation.

One might hope that numpy.can_cast(from, totype) would do the job, but, alas,

np.can_cast("a",np.dtype("O"))
> TypeError: did not understand one of the types; 'None' not accepted

3 个答案:

答案 0 :(得分:0)

当我正确理解时,整个numpy数组总是某种类型,并且我建议在数组中不能有混合项:

isinstance(my_array, np.ndarray)`

这就是我在我的单元测试中所做的事情:

assert isinstance(groups, np.ndarray)

在我的生产代码中,我这样做

groups = [-1, -1, 0, 2]
groups = np.asarray(g, dtype=np.uint8)

编辑:我最初误解了这个问题。您想检查是否可以在数组中插入ceratin变量。好吧,让我们试试这个:

def is_var_allowed(x):
    try:
        x = np.uint8(x)
        return True
    except ValueError:
        return False

def main():
    my_arr = np.ones((5,), dtype=np.uint8))
    x = 7
    if is_var_allowed(x):
       my_arr.put(3, x)

这将产生一个数组[1 1 1 7 1]。可以通过给函数is_var_allowed提供dtype作为参数来概括这一点:

def is_var_allowed(x, func):
    try:
        x = func(x)
        return True
    except ValueError:
        return False

def main():
    my_uint_arr = np.ones((5,), dtype=np.uint8))
    x = 7
    if is_var_allowed(x, np.uint8):
       my_uint8_arr.put(3, x)

    my_char_arr = np.char.array((5,1))
    y = "Hallo"
    if is_var_allowed(y, np.char)
        my_char_arr[:] = y

答案 1 :(得分:0)

我不知道如何直接判断,因为有dtype in numpy这么多,相反,您可以使用以下函数来判断:

def np_isinstance(value, np_data):
    """
    This function for 1D np_data
    """
    flag = False
    try:
        tmp = np_data[0] + value
        flag = True
    except:
        pass
    return flag

答案 2 :(得分:0)

can_cast复制您的测试用例:

In [213]: np.can_cast(type("a"), np.array(["a","b"]).dtype)
Out[213]: True
In [214]: np.can_cast(type(1), np.array(["a","b"]).dtype)
Out[214]: False
In [215]: np.can_cast(type("a"), np.array([1,2,3]).dtype)
Out[215]: False
In [217]: np.can_cast(type(1), np.array([1,2,3]).dtype)
Out[217]: True
In [219]: np.can_cast(type(1), np.dtype("O"))
Out[219]: True
In [220]: np.can_cast(type("a"), np.dtype("O"))
Out[220]: True

请注意,我将typedtype匹配。