简体   繁体   English

如何检查numpy数组是否包含空列表

[英]How to check if numpy array contains empty list

Here is a sample code for data这是数据的示例代码

import numpy as np
myList1 = np.array([1,1,1,[1],1,1,[1],1,1])
myList2 = np.array([1,1,1,[],1,1,[],1,1])

To see if elements in myList1 equals to [1] I could do this:要查看 myList1 中的元素是否等于 [1],我可以这样做:

myList1 == [1]

But for myList2, to see if elements in myList2 equals to [] I COULDN'T do this:但是对于 myList2,要查看 myList2 中的元素是否等于 [] 我不能这样做:

myList2 == []

I had to do:我必须做:

[x == [] for x in myList2]

Is there another way to look for elements in lists that will also handle empty lists?是否有另一种方法可以在列表中查找也可以处理空列表的元素? some other function in numpy or python that I could use?我可以使用 numpy 或 python 中的其他一些函数吗?

An array with a mix of numbers and lists (empty or not) is object dtype .混合了数字和列表(空或非空)的数组是object dtype This is practically a list ;这实际上是一个list fast compiled numpy math no longer works.快速编译的numpy数学不再有效。 The only practical alternative to a list comprehension is np.frompyfunc .列表np.frompyfunc的唯一实用替代方案是np.frompyfunc

Write a small function that can distinguish between a number and list and length of list, and apply that to the array.编写一个可以区分数字和列表以及列表长度的小函数,并将其应用于数组。 If it returns True for an empty list, then np.where will identify the location如果它为空列表返回 True,则np.where将标识位置

In [41]: myList1 = np.array([1,1,1,[1],1,1,[1],1,1]) 
    ...: myList2 = np.array([1,1,1,[],1,1,[],1,1])                              

Develop a function that returns True for a empty list, False otherwise:开发一个函数,对于空列表返回 True,否则返回 False:

In [42]: len(1)                                                                 
...
TypeError: object of type 'int' has no len()
In [43]: len([])                                                                
Out[43]: 0

In [44]: def foo(item): 
    ...:     try: 
    ...:         return len(item)==0 
    ...:     except TypeError: 
    ...:         pass 
    ...:     return False 
    ...:                                                                        
In [45]: foo([])                                                                
Out[45]: True
In [46]: foo([1])                                                               
Out[46]: False
In [47]: foo(1)                                                                 
Out[47]: False

Apply it to the arrays:将其应用于数组:

In [48]: f=np.frompyfunc(foo,1,1)                                               
In [49]: f(myList1)                                                             
Out[49]: 
array([False, False, False, False, False, False, False, False, False],
      dtype=object)
In [50]: np.where(f(myList1))                                                   
Out[50]: (array([], dtype=int64),)
In [51]: np.where(f(myList2))                                                   
Out[51]: (array([3, 6]),)

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

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