以numpy索引多个非相邻范围 [英] Index multiple, non-adjacent ranges in numpy

查看:225
本文介绍了以numpy索引多个非相邻范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一维numpy数组(或向量)中选择多个不相邻的范围.

I'd like to select multiple, non-adjacent ranges from a 1d numpy array (or vector).

假设:

>>> idx = np.random.randint(100, size=10)
array([82,  9, 11, 94, 31, 87, 43, 77, 49, 50])

这当然有效:

>>> idx[0:3]
array([82,  9, 11])

这可以通过单个索引获取:

And this works to fetch via individual indices:

>>> idx[[0,3,4]]
array([82, 94, 31])

但是,如果我想选择范围0:37:怎么办?

But what if I want to select the ranges 0:3, and 7:?

我尝试过:

>>> idx[[0:3,7:]]
SyntaxError: invalid syntax

是否有一种简单的方法来执行此操作,或者我需要分别生成它们并进行连接?

Is there a simple way to do this, or do I need to generate them separately and concatenate?

推荐答案

您需要在索引之前或之后进行串联. np.r_轻松

You need to concatenate, either before or after indexing. np.r_ makes it easy

In [116]: idx=np.array([82,  9, 11, 94, 31, 87, 43, 77, 49, 50])
In [117]: np.r_[0:3,7:10]
Out[117]: array([0, 1, 2, 7, 8, 9])
In [118]: idx[np.r_[0:3,7:10]]
Out[118]: array([82,  9, 11, 77, 49, 50])

np.r_扩展切片并将它们连接起来.

np.r_ expands the slices and concatenates them.

您可以混合切片和列表:

You can mix slices and lists:

In [120]: np.r_[0:3,7:10,[0,3,4]]
Out[120]: array([0, 1, 2, 7, 8, 9, 0, 3, 4])

在索引编制之前进行连接可能比在索引编制之后进行连接快,但是对于这样的一维数组,我认为这种区别并不明显.

Concatenating before indexing is probably faster than after, but for 1d array like this, I don't think the difference is significant.

这篇关于以numpy索引多个非相邻范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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