简体   繁体   English

使用numpy获取切片后剩余的内容

[英]Get what's remaining after a slice using numpy

I have a numpy matrix where one row for example looks like the following: 我有一个numpy矩阵,例如一行如下所示:

|0 1 2 3 4 5 6 7 8|

I can get a certain piece of the array eg. 我可以得到数组的某个部分,例如。 [3,4,5] which I need for one purpose using numpy slicing a[0,3:6] . [3,4,5]我需要使用numpy切片a[0,3:6]

Is there anything builtin that will allow me to also get everything not in that range with it? 是否有任何内置功能可以使我也获得此范围之外的所有功能? Like [0,1,2,6,7,8] [0,1,2,6,7,8]

One approach with boolean indexing - boolean indexing一种方法-

a[~np.in1d(np.arange(a.size),r)]

Sample run - 样品运行-

In [174]: a
Out[174]: array([10, 11, 12, 13, 14, 15, 16, 17, 18])

In [175]: r
Out[175]: [3, 4, 5]

In [176]: a[~np.in1d(np.arange(a.size),r)]  # Without r
Out[176]: array([10, 11, 12, 16, 17, 18])

In [177]: a[r]  # With r
Out[177]: array([13, 14, 15])

Another with integer array indexing - 另一个具有integer array indexing -

a[np.setdiff1d(np.arange(a.size),r)]

Another way would be concatenating slices on either sides of the original slice - 另一种方法是在原始切片的两侧连接切片-

np.concatenate((a[:r[0]], a[r[-1]+1:]))

There's some ambiguity in your question and example. 您的问题和示例中有些含糊。 Are you selecting elements by value or index? 您是按值还是按索引选择元素? And should we take slice literally? 我们应该从字面上slice吗?

Taking slice literally: 从字面上看slice

In [10]: x=np.arange(10)   # stick with the ambiguous input for now
In [11]: x[3:6]
Out[11]: array([3, 4, 5])

np.delete is a handy tool if selecting elements by position. 如果按位置选择元素, np.delete是一个方便的工具。 It's general purpose, and can use slice as well as list inputs: 这是通用的,可以使用slicelist输入:

In [13]: np.delete(x,slice(3,6))
Out[13]: array([0, 1, 2, 6, 7, 8, 9])
In [14]: np.delete(x,[3,4,5])
Out[14]: array([0, 1, 2, 6, 7, 8, 9])

np.in1d is useful if you want to select elements by value. 如果np.in1d值选择元素, np.in1d很有用。

Boolean masking is also a good tool to know and use. 布尔掩码也是了解和使用的好工具。


delete uses different methods depending on the inputs. delete根据输入使用不同的方法。 For a simple slice I believe it uses the equivalent of: 对于一个简单的切片,我相信它使用的等效项是:

In [15]: np.concatenate((x[:3],x[6:]))
Out[15]: array([0, 1, 2, 6, 7, 8, 9])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM