给定一个值数组和一个有效的索引数组,我想得到所有其他的索引。你知道吗
正在寻找一种可行的方法,但下面是一个解决方案的示例,并阐明了我要实现的目标:
A = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g']) # Array of values. Shape: (7,)
B = np.array([0,3,5]) # Array of indices.
# Looking for a more elegant way to do this following line
C = np.array([i for i in range(len(A)) if i not in B]) # Array indices not in B
# Expected Output: C = [1, 2, 4, 6]
编辑:确定解决方案的基准
A = np.ones(10000)
B = np.random.random_integers(low=0, high=len(A) - 1, size=8000)
t1 = time()
mask = np.ones(len(A), dtype=bool)
mask[B] = False
C = np.arange(len(A))[mask]
t1 = time() - t1
t2 = time()
C = np.delete(np.arange(A.size), B)
t2 = time() - t2
t3 = time()
C = np.array([i for i in range(len(A)) if i not in B])
t3 = time() - t3
t4 = time()
C = set(np.arange(len(A))).difference(B)
t4 = time() - t4
print("T1: %.5f" % np.round(t1, 5))
print("T2: %.5f" % np.round(t2, 5))
print("T3: %.5f" % np.round(t3, 5))
print("T4: %.5f" % np.round(t4, 5))
结果(数值随B
中指数数量的变化而变化,但最快的总是T1
:
T1: 0.00011
<;<;<;多次运行上述脚本,这始终是最快的。第二种方法总是有点落后。T2: 0.00017
T3: 0.05746
<;<;列表理解花费的时间最多。即使在移除np.数组.T4: 0.00158
T2
),因为它是一个单行程序,所用的时间(几乎)与最快的方法相同。你知道吗
可以使用
np.delete
从可以使用np.arange
创建的其他索引列表中删除B
项:演示:
我不确定这是不是Python,但它是更Numpythonic(如果这是一件事)。首先,数组的查找是O(N)。其次,陷入Python迭代(在您的列表理解中)首先破坏了使用numpy数组的目的。你知道吗
编辑
一些基准。你知道吗
令人惊讶的是,@Kasramvd的解决方案并不比我的快,尽管它要干净一些。考虑到这个结果,如果
np.delete
实际上是一个与我实现的逻辑相同的瘦包装器,我也不会感到惊讶。因此,我没有理由选择我的解决方案而不是@Kasramvd的相关问题 更多 >
编程相关推荐