选择数组中N个均匀间隔的元素,包括第一个和最后一个 [英] Select N evenly spaced out elements in array, including first and last

查看:64
本文介绍了选择数组中N个均匀间隔的元素,包括第一个和最后一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任意长度的数组,我想选择其中的 N 个元素,均匀间隔(大约,因为 N 可能是偶数,数组长度可能是素数等),其中包括第一个 arr[0] 元素和最后一个 arr[len-1] 元素.

示例:

<预><代码>>>>arr = np.arange(17)>>>阿尔数组([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])

然后我想创建一个像下面这样的函数来获取数组中均匀分布的 numElems,它必须包括第一个和最后一个元素:

GetSpacedElements(numElems = 4)>>>返回 0、5、11、16

这有意义吗?

我尝试过 arr[0:len:numElems](即使用数组 start:stop:skip 符号)和一些细微的变化,但我没有得到我在这里寻找的东西:

<预><代码>>>>arr[0:len:numElems]数组([ 0, 4, 8, 12, 16])

<预><代码>>>>arr[0:len:numElems+1]数组([ 0, 5, 10, 15])

我并不关心中间元素是什么,只要它们均匀地间隔开,比方说的索引为 1 即可.但是获取正确数量的元素(包括索引零和最后一个索引)至关重要.

解决方案

要获取均匀间隔索引的列表,请使用 np.linspace:

idx = np.round(np.linspace(0, len(arr) - 1, numElems)).astype(int)

接下来,索引回arr以获得相应的值:

arr[idx]

在转换为整数之前总是使用舍入.在内部,linspace 在提供 dtype 参数时调用 astype.因此,此方法等同于:

# 这只是截断非整数部分idx = np.linspace(0, len(array) - 1, numElems).astype(int)idx = np.linspace(0, len(arr) - 1, numElems, dtype='int')

I have an array of arbitrary length, and I want to select N elements of it, evenly spaced out (approximately, as N may be even, array length may be prime, etc) that includes the very first arr[0] element and the very last arr[len-1] element.

Example:

>>> arr = np.arange(17)
>>> arr
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16])

Then I want to make a function like the following to grab numElems evenly spaced out within the array, which must include the first and last element:

GetSpacedElements(numElems = 4)
>>> returns 0, 5, 11, 16

Does this make sense?

I've tried arr[0:len:numElems] (i.e. using the array start:stop:skip notation) and some slight variations, but I'm not getting what I'm looking for here:

>>> arr[0:len:numElems]
array([ 0,  4,  8, 12, 16])

or

>>> arr[0:len:numElems+1]
array([ 0,  5, 10, 15])

I don't care exactly what the middle elements are, as long as they're spaced evenly apart, off by an index of 1 let's say. But getting the right number of elements, including the index zero and last index, are critical.

解决方案

To get a list of evenly spaced indices, use np.linspace:

idx = np.round(np.linspace(0, len(arr) - 1, numElems)).astype(int)

Next, index back into arr to get the corresponding values:

arr[idx]

Always use rounding before casting to integers. Internally, linspace calls astype when the dtype argument is provided. Therefore, this method is NOT equivalent to:

# this simply truncates the non-integer part
idx = np.linspace(0, len(array) - 1, numElems).astype(int)
idx = np.linspace(0, len(arr) - 1, numElems, dtype='int')

这篇关于选择数组中N个均匀间隔的元素,包括第一个和最后一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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