简体   繁体   English

从numpy数组中查找和删除某些元素的有效方法

[英]Effective way to find and delete certain elements from a numpy array

I have a numpy array with some positive numbers and some -1 elements. 我有一个带有一些正数和一些-1元素的numpy数组。 I want to find these elements with -1 values, delete them and store their indeces. 我想找到具有-1值的这些元素,删除它们并存储其指数。

One way of doing it is iterating through the array and cheking if the value is -1 . 一种实现方法是遍历数组并检查值是否为-1 Is this the only way? 这是唯一的方法吗? If not, what about its effectivness? 如果不是,那么其有效性如何? Isn't there a more effective python tool then? 难道没有更有效的python工具吗?

With numpy.argwhere() and numpy.delete() routines: 使用numpy.argwhere()numpy.delete()例程:

import numpy as np

arr = np.array([1, 2, 3, -1, 4, -1, 5, 10, -1, 14])
indices = np.argwhere(arr == -1).flatten()
new_arr = np.delete(arr, indices)

print(new_arr)            # [ 1  2  3  4  5 10 14]
print(indices.tolist())   # [3, 5, 8]

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.argwhere.html https://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html https://docs.scipy.org/doc/numpy-1.13.0/reference/produced/numpy.argwhere.html https://docs.scipy.org/doc/numpy/reference/produced/numpy.delete.html

import numpy as np
yourarray=np.array([4,5,6,7,-1,2,3,-1,9,-1]) #say
rangenumpyarray=np.arange(len(yourarray)) # to create a column adjacent to your array of range
arra=np.hstack((rangenumpyarray.reshape(-1,1),yourarray.reshape(-1,1))) # combining both arrays as two columns
arra[arra[:,1]==-1][:,0]  # learn boolean indexing

Use a combination of np.flatnonzero and simple boolean indexing . 结合使用np.flatnonzero和简单的布尔索引

x = array([ 0,  0, -1,  0,  0, -1,  0, -2,  0,  0])
m = x != -1  # generate a mask

idx = np.flatnonzero(~m)
x = x[m]
idx
array([2, 5])

x
array([ 0,  0,  0,  0,  0, -2,  0,  0])

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

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