[英]Return numpy matrix without specific row
I have a matrix [nx 3]. 我有一个矩阵[nx 3]。 I want to specify row: 我想指定行:
test_row = np.array([a, b, c])
and delete it from my matrix. 并从我的矩阵中删除它。
Is there a better way than using for and np.array_equal
over whole matrix? 有没有比在整个矩阵上使用for和np.array_equal
更好的方法?
An alternative to deleting the desired rows is, if you happen to know the index of the row that you want to remove , you can simply slice the remaining rows and concatenate it into a matrix as in the example below: 在删除所需的行另一种方法是,如果你碰巧知道要删除 ,你可以简单地切开剩余的行并将其连接成一个矩阵,如下面的例子中,行索引:
In [8]: arr = np.arange(5*3).reshape(5, 3)
In [9]: arr
Out[9]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14]])
In [10]: remove_row_idx = 2
In [11]: np.vstack((arr[:remove_row_idx, :], arr[remove_row_idx+1:,]))
Out[11]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 9, 10, 11],
[12, 13, 14]])
In [318]: arr = np.arange(24).reshape(8,3)
In [319]: test = np.array([6,7,8])
A whole-array comparison between the 2: 2之间的整数组比较:
In [322]: np.isin(arr,test)
Out[322]:
array([[False, False, False],
[False, False, False],
[ True, True, True],
[False, False, False],
[False, False, False],
[False, False, False],
[False, False, False],
[False, False, False]])
Find the row where all terms match: 找到所有术语匹配的行:
In [323]: np.isin(arr,test).all(axis=1)
Out[323]: array([False, False, True, False, False, False, False, False])
Use its inverse as the mask to select the keeper rows: 使用其反转作为掩码来选择守护者行:
In [324]: arr[~_]
Out[324]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17],
[18, 19, 20],
[21, 22, 23]])
isin
actually is in1d
plus a reshape: isin
实际上是in1d
加上重塑:
In [327]: np.in1d(arr,test)
Out[327]:
array([False, False, False, False, False, False, True, True, True,
False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False])
In [328]: np.in1d(arr,test).reshape(arr.shape)
Out[328]:
array([[False, False, False],
[False, False, False],
[ True, True, True],
[False, False, False],
[False, False, False],
[False, False, False],
[False, False, False],
[False, False, False]])
This broadcasted comparison also works: 这种广播比较也有效:
(arr[:,None,:]==test[None,:,None]).any(axis=1).all(axis=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.