np.delete删除数组内容

np.delete

numpy.delete(arr, obj, axis=None)

  • 返回一个新的array,删除掉obj,沿着axis方向
  • axis : int, optional
  • The axis along which to delete the subarray defined by obj. If axis is None, obj is applied to the flattened array.(如果不加上axis的话会自动把这个array拉平)
  • axis = 0:删除数组的行
  • axis = 1: 删除数组的列
  • axis = none: 把整个数组平铺之后按索引删除
1
2
3
4
5
6
7
8
9
10
11
12
import numpy as np

ids = [[3], [34], [5]]
ids_o = [[3], [31]]

remove_list = filter(lambda i: i not in ids, ids_o)
# print(np.asarray(ids))
for i in remove_list:
index = np.where(np.asarray(ids_o) == i)[0]
print("index = ", index)
ids = np.delete(ids, index, axis = 0)
print("new ids = \n", ids)

结果:

1
2
3
4
index =  [1]
new ids =
[[3]
[5]]

如果把上面改成

1
ids = np.delete(ids, 0, axis = 1)

即为删除数组的第0列,结果是 [ ] (因为只有一列)

如果改成

1
ids = np.delete(ids, index, axis = None)

结果为:

1
2
new ids = 
[3 5]