2

如何检查给定值是否可以存储在numpy数组中?

例如:

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)

我想要一个np_isinstance可以做到这一点的函数:

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

到目前为止,我设法想出了

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

但这似乎是错误的,因为它array在每次调用时分配一个。

人们可能希望numpy.can_cast(from, totype)能完成这项工作,但是,唉,

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

3 回答 3

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

请注意,我将 atype与 a匹配dtype

于 2017-06-12T19:25:58.993 回答
0

When I'm understanding correctly, that the whole numpy array is always of a certain type and there cannot be mixed items in the array I would suggest doing:

isinstance(my_array, np.ndarray)`

That's what I'm doing in my unittest:

assert isinstance(groups, np.ndarray)

while in my production code i do this

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

Edit: I misunderstood the question at first. You want to check if a ceratin variable can be inserted in the array. Well let's try this then:

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)

This will result in an array [1 1 1 7 1]. One could generalize this by giving the function is_var_allowed also a dtype as parameter like this:

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
于 2017-06-12T17:15:17.257 回答
0

我不知道如何直接判断,因为numpy 的 dtype 太多了,你可以使用下面的函数来判断:

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
于 2017-06-12T17:28:26.343 回答