简体   繁体   English

将 np.where 与 OOP 一起使用

[英]Using np.where with OOP

I have create an numpy array in which all the cells values are objects.我创建了一个 numpy 数组,其中所有单元格值都是对象。 I want to use np.where conditions but it is not working as I want to check the equivalent conditions for object attributes.我想使用 np.where 条件,但它不起作用,因为我想检查 object 属性的等效条件。 The object class looks similar to the one below: object class 与下图类似:

class Cell():
     def __init__(self):
         self.value = 'ABC'
     def __repr__(self):
         return self.value

Now I have 2D numpy array with all the cell equivalent to this cell class, and I want to check if cell.value == 'ABC'.现在我有 2D numpy 数组,所有单元格都与此单元格 class 等效,我想检查 cell.value == 'ABC'。 The numpy array look like, numpy 阵列看起来像,

array([[M, M, M, M],
       [M, 'ABC', M, M],
       [M, M, M, M],
       [M, M, M, 'ABC'],
       [M, M, M, M]], dtype=object)

If I try to run np.where(temp == 'ABC'), I get the following output:如果我尝试运行 np.where(temp == 'ABC'),我会得到以下 output:

(array([], dtype=int64), array([], dtype=int64))

And if I run the command np.where(temp.value == 'ABC'), I get the following error:如果我运行命令 np.where(temp.value == 'ABC'),我会收到以下错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-70-073cbaaed538> in <module>
----> 1 np.where(temp.value =='ABC')

AttributeError: 'numpy.ndarray' object has no attribute 'value'

How can I use np.where with OOP?如何将 np.where 与 OOP 一起使用?

You are comparing with an object ('ABC') from str class with an object from '__main__.Cell' class.您正在与str class 中的 object ('ABC') 与来自'__main__.Cell' ZA2F2ED4F8EBC2ABC1BDCZC2 的 object 进行比较。 (try checking with type(Cell()) (尝试检查type(Cell())

A fix is simply changing type with np.array.astype()一个修复就是用np.array.astype()改变类型

arr = np.array([['M', Cell(),'M'], 
                ['M', Cell(),'M'], 
                [Cell(),'M' ,'M']])

np.where(arr.astype(str)=='ABC')
(array([0, 1, 2]), array([1, 1, 0]))

Additionally,此外,

You can check type of each element individually in your array by -您可以通过以下方式单独检查数组中每个元素的类型 -

np.vectorize(type)(arr)
array([[<class 'str'>, <class '__main__.Cell'>, <class 'str'>],
       [<class 'str'>, <class '__main__.Cell'>, <class 'str'>],
       [<class '__main__.Cell'>, <class 'str'>, <class 'str'>]],
      dtype=object)

Notice, that some of them are objects of class str which you want to use for comparison but others are Cell class objects.请注意,其中一些是您想要用于比较的 class str的对象,而其他的是Cell class 对象。

I think you need to traverse through the whole array to check if something is equal to 'ABC'.我认为您需要遍历整个数组以检查某些内容是否等于“ABC”。 The code for the same is below:相同的代码如下:

m =[]
for i in range(temp.shape[0]):
    m.append([])
    for j in range(temp.shape[1]):
        m[i].append(temp[i,j].value == 'ABC')
np.where(m)

In this case, you won't have the computation advantage of using np.where, as you need to traverse through the whole array using for loops.在这种情况下,您将没有使用 np.where 的计算优势,因为您需要使用 for 循环遍历整个数组。

In [38]: class Cell():
    ...:      def __init__(self):
    ...:          self.value = 'ABC'
    ...:      def __repr__(self):
    ...:          return self.value
    ...: 

A list of these objects:这些对象的列表:

In [39]: alist = [Cell(),Cell(),Cell()]
In [40]: [c.value for c in alist]
Out[40]: ['ABC', 'ABC', 'ABC']
In [41]: alist.value
Traceback (most recent call last):
  File "<ipython-input-41-e136813b0fd2>", line 1, in <module>
    alist.value
AttributeError: 'list' object has no attribute 'value'

An array of the same:一个相同的数组:

In [42]: arr = np.array(alist)
In [43]: arr
Out[43]: array([ABC, ABC, ABC], dtype=object)
In [44]: arr.value
Traceback (most recent call last):
  File "<ipython-input-44-bfedc572e969>", line 1, in <module>
    arr.value
AttributeError: 'numpy.ndarray' object has no attribute 'value'

Same problem as with this list.与此列表相同的问题。 Just because the elements have some attribute, it does not mean that a list or array has that attribute.仅仅因为元素具有某些属性,并不意味着列表或数组具有该属性。 That's not how Python's OOP works.这不是 Python 的 OOP 的工作方式。

In [45]: [c.value for c in arr]
Out[45]: ['ABC', 'ABC', 'ABC']

An alternative to the list comprehension:列表理解的替代方法:

In [46]: np.frompyfunc(lambda x: x.value, 1,1)(arr)
Out[46]: array(['ABC', 'ABC', 'ABC'], dtype=object)

This may be convenient in some cases, but it is not faster.这在某些情况下可能很方便,但速度并不快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM