从python中的ndarray中删除行

时间:2022-12-27 04:15:17

I have a 2D - array A, which contains the x and y coordinates of points

我有一个2D数组A,它包含点的x和y坐标

array([[ 0,  0],
       [ 0,  0],
       [ 0,  0],
       [ 3,  4],
       [ 4,  1],
       [ 5, 10],
       [ 9,  7]])

as you can see the point ( 0 , 0 ) appears more often.

正如您所见,点(0,0)更频繁出现。

I want to delete this point so that the array looks like this:

我想删除这一点,以便数组看起来像这样:

array([[ 3,  4],
       [ 4,  1],
       [ 5, 10],
       [ 9,  7]])

Since the array in real is very huge, it is very important to do this without for loops, otherwise it takes very long.

由于实数中的数组非常庞大,因此在没有for循环的情况下执行此操作非常重要,否则需要很长时间。

I'm new to python but i'm used to matlab, where I can solve it very easily with:

我是python的新手,但我已经习惯了matlab,在那里我可以很容易地解决它:

A (A(:,1) == 0 & A(:,2) == 0, :) = []

I thought it is almost the same or very similar in python, but I can't figure it out - am totally stuck. Errors like "use a.any()/all()" or "ufunc "bitwise_and" not supported for the input types" appear and I don't know what I should change.

我认为它在python中几乎相同或非常相似,但我无法弄清楚 - 我完全卡住了。出现“使用a.any()/ all()”或“ufunc”bitwise_和“输入类型不支持”等错误,我不知道应该更改什么。

1 个解决方案

#1


1  

Technically what you are doing in MATLAB is not deleting elements from A. What you are actually doing is creating a new array that lacks the elements of A. It is equivalent to:

从技术上讲,你在MATLAB中所做的不是从A中删除元素。你实际在做的是创建一个缺少A元素的新数组。它相当于:

>> A = A (A(:,1) ~= 0 | A(:,2) ~= 0, :);

You can do exactly the same thing in numpy:

你可以在numpy中做同样的事情:

>>> a = a[(a[:,0] != 0) | (a[:,1] != 0), :]

However, thanks to numpy's automatic broadcasting, you can make this simpler:

但是,感谢numpy的自动广播,你可以更简单:

>>> a = a[(a != [0, 0]).any(1)]

This will work for any target array so long as it has the same number of columns as a.

这适用于任何目标数组,只要它具有与a相同的列数。

#1


1  

Technically what you are doing in MATLAB is not deleting elements from A. What you are actually doing is creating a new array that lacks the elements of A. It is equivalent to:

从技术上讲,你在MATLAB中所做的不是从A中删除元素。你实际在做的是创建一个缺少A元素的新数组。它相当于:

>> A = A (A(:,1) ~= 0 | A(:,2) ~= 0, :);

You can do exactly the same thing in numpy:

你可以在numpy中做同样的事情:

>>> a = a[(a[:,0] != 0) | (a[:,1] != 0), :]

However, thanks to numpy's automatic broadcasting, you can make this simpler:

但是,感谢numpy的自动广播,你可以更简单:

>>> a = a[(a != [0, 0]).any(1)]

This will work for any target array so long as it has the same number of columns as a.

这适用于任何目标数组,只要它具有与a相同的列数。