python - 如何在标识空列表的 numpy 布尔数组中创建空列表?
问题描述
我正在尝试创建一个布尔数组来标识数组中的空列表。我做了以下代码:
import numpy as np
from scipy.spatial import cKDTree
rand_points = np.random.rand(5,3)
other_points = np.zeros((5,3))
for i in range(3):
other_points[:,i] = rand_points[:,i] * 2
randTree = cKDTree(rand_points)
nearPoints = cKDTree.query_ball_point(randTree, other_points, 0.6)
nearPoints
可以产生以下输出:
array([list([]), list([]), list([2]), list([]), list([])], dtype=object)
我想生成一个布尔数组,它选择等于list([ ])
as 的元素True
。我尝试了多种方法,但都没有成功,例如:
nearPoints == None
我将如何正确创建布尔数组?
解决方案
如果您有带有 的数组,则没有太多性能可言dtype=object
,显然这确实是cKDTree
给您的。所以不妨用列表理解创建数组:
>>> np.array([len(lst)==0 for lst in nearPoints])
array([ True, True, True, False, True])
或者,如果您更喜欢map
列表理解(我不喜欢):
~np.fromiter(map(len, nearPoints), dtype=bool)
在更高的层次上,对于这样一个列表数组的向量化操作,您可能无能为力,因此您可能最终还是会遍历该数组。但是你可以做
for lst in nearPoints:
if not lst:
# skip empty list cases
continue
推荐阅读
- python - itertools Permutation:仅返回特定组合
- javascript - 在javascript中为每3个键分块一个对象
- javascript - 如何使用谷歌脚本遍历所有工作表?
- ubuntu - 重新上传目标文件后不执行 CRON TAB
- service-layer - SAP B1 服务层登录 POST 请求提供错误代码 -304 和空消息
- python - 在 Windows 上安装 apache-airflow 时出错
- javascript - 原型链中“new person()”和“prototype.person”之间的区别?
- c++ - 如果从环境变量运行,如何将文件路径作为参数传递给程序?C++
- reactjs - 测试结果 - 类名未更新
- python - 训练 Fasttext 模型