从numpy数组中删除一个元素

时间:2018-06-07 06:06:33

标签: python pandas numpy numpy-ndarray

我正在使用numpy array,如下所示:

  input_series =  ['BUY' 'SELL' 'BUY' 'SELL' 'BUY' 'SELL' 'SELL' 'SELL' 'BUY' 'SELL' nan nan
     nan nan nan nan nan nan nan]

我在数组中搜索特定值,如果元素存在则删除

我这样做了如下:

delete_indices = list()
val = ['BUY','SELL','No','YES']
found_index = np.where(lowercase_series_nparray == val)                                                
delete_indices.append(found_index)

delete_indices如下:

[(array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([0, 2, 4, 8], dtype=int64),), (array([1, 3, 5, 6, 7, 9], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),)]

Aftre我试图删除:

new_output_series = numpy.delete(input_series, delete_indices)

但错误为setting an array element with a sequence.

2 个答案:

答案 0 :(得分:4)

如果来自这样的数组:

input_series = np.array(['BUY', 'a', 'b', 'SELL', 'YES', 'SELL', 'No', 'c', 'd', 'SELL'])

您想删除这些元素:

['BUY','SELL','No','YES']

只需将它们设置为数组:

val = np.array(['BUY','SELL','No','YES'])

然后:

new_output_series = np.setdiff1d(input_series,val)

输出:

 ['a' 'b' 'c' 'd']

答案 1 :(得分:1)

下面的语句为您提供了所需的索引:

 found_index = np.in1d(input_series, val).nonzero()[0]

然后:

 new_array = numpy.delete(input_series, found_index)