numpy从列表列表中删除列表元素 [英] numpy delete list element from list of lists

查看:1202
本文介绍了numpy从列表列表中删除列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy数组:

I have an array of numpy arrays:

a = [[1, 2, 3, 4], [1, 2, 3, 5], [2, 5, 4, 3], [5, 2, 3, 1]]

我需要从a中查找并删除特定列表:

I need to find and remove a particular list from a:

rem = [1,2,3,5]

numpy.delete(a,rem)无法返回正确的结果.我需要能够返回:

numpy.delete(a,rem) does not return the correct results. I need to be able to return:

[[1, 2, 3, 4], [2, 5, 4, 3], [5, 2, 3, 1]]

numpy可以吗?

推荐答案

您尝试删除列表了吗?

In [84]: a = [[1, 2, 3, 4], [1, 2, 3, 5], [2, 5, 4, 3], [5, 2, 3, 1]]
In [85]: a
Out[85]: [[1, 2, 3, 4], [1, 2, 3, 5], [2, 5, 4, 3], [5, 2, 3, 1]]
In [86]: rem = [1,2,3,5]
In [87]: a.remove(rem)
In [88]: a
Out[88]: [[1, 2, 3, 4], [2, 5, 4, 3], [5, 2, 3, 1]]

remove与值匹配.

np.delete使用索引而不是值.它还返回一个副本;它没有发挥作用.结果是一个数组,而不是一个嵌套列表(np.delete在对其进行操作之前将输入转换为数组).

np.delete works with an index, not value. Also it returns a copy; it does not act in place. And the result is an array, not a nested list (np.delete converts the input to an array before operating on it).

In [92]: a = [[1, 2, 3, 4], [1, 2, 3, 5], [2, 5, 4, 3], [5, 2, 3, 1]]
In [93]: a1=np.delete(a,1, axis=0)
In [94]: a1
Out[94]: 
array([[1, 2, 3, 4],
       [2, 5, 4, 3],
       [5, 2, 3, 1]])

这更像列表pop:

In [96]: a = [[1, 2, 3, 4], [1, 2, 3, 5], [2, 5, 4, 3], [5, 2, 3, 1]]
In [97]: a.pop(1)
Out[97]: [1, 2, 3, 5]
In [98]: a
Out[98]: [[1, 2, 3, 4], [2, 5, 4, 3], [5, 2, 3, 1]]

要按值delete,首先需要找到所需行的索引.使用整数数组并不难.浮点数比较棘手.

To delete by value you need first find the index of the desired row. With integer arrays that's not too hard. With floats it is trickier.

=========

=========

但是您无需使用delete来在numpy中执行此操作;布尔索引工作:

But you don't need to use delete to do this in numpy; boolean indexing works:

In [119]: a = [[1, 2, 3, 4], [1, 2, 3, 5], [2, 5, 4, 3], [5, 2, 3, 1]]
In [120]: A = np.array(a)     # got to work with array, not list
In [121]: rem=np.array([1,2,3,5])

简单比较;广播rem以匹配行

Simple comparison; rem is broadcasted to match rows

In [122]: A==rem
Out[122]: 
array([[ True,  True,  True, False],
       [ True,  True,  True,  True],
       [False, False, False, False],
       [False,  True,  True, False]], dtype=bool)

找到所有元素都匹配的行-这是我们要删除的行

find the row where all elements match - this is the one we want to remove

In [123]: (A==rem).all(axis=1)
Out[123]: array([False,  True, False, False], dtype=bool)

只需not它,并使用它为A编制索引:

Just not it, and use it to index A:

In [124]: A[~(A==rem).all(axis=1),:]
Out[124]: 
array([[1, 2, 3, 4],
       [2, 5, 4, 3],
       [5, 2, 3, 1]])

(原始的A不变).

np.where可用于将布尔值(或其倒数)转换为索引.有时很方便,但通常不是必需的.

np.where can be used to convert the boolean (or its inverse) to indicies. Sometimes that's handy, but usually it isn't required.

这篇关于numpy从列表列表中删除列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆