如何在识别空列表的numpy布尔数组中创建空列表?

时间:2018-10-28 20:37:04

标签: python numpy scipy kdtree scipy-spatial

我正在尝试创建一个布尔数组,该数组标识数组中的空列表。我做了以下代码:

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([ ])的元素作为True。我尝试了多种方法,但没有成功,例如:

nearPoints == None

如何正确创建布尔数组?

2 个答案:

答案 0 :(得分:1)

如果您使用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

答案 1 :(得分:1)

您可以简单地执行以下操作:

import tensorflow as tf


def condition(i, x):
    return tf.less(i, 10)


def body_1(my_ops):
    def b(i, x):
        stacked_results = tf.stack([op(x) for op in my_ops])
        gather_idx = tf.mod(i, 2)
        return [i + 1, tf.gather(stacked_results, gather_idx)]

    return b


def body_2(my_ops):
    def b(i, x):
        nb_ops = len(my_ops)
        pred_fn_pairs = [(tf.equal(tf.mod(i, nb_ops), 0), lambda: my_ops[0](x)),
                         (tf.equal(tf.mod(i, nb_ops), 1), lambda: my_ops[1](x))]
        result = tf.case(pred_fn_pairs)
        return [i + 1, result]

    return b


my_ops = [lambda x: tf.Print(x + 1, [x, 1]),
          lambda x: tf.Print(x + 2, [x, 2])]
i = tf.constant(0)
x = tf.constant(0)
r = tf.while_loop(condition, body_2(my_ops), [i, x])  # See the difference with body_1

with tf.Session() as sess:
    i, x = sess.run(r)
    print(x)  # Prints 15 = 5*2 + 5*1