选择数组中N个均匀间隔的元素,包括第一个和最后一个 [英] Select N evenly spaced out elements in array, including first and last
问题描述
我有一个任意长度的数组,我想选择其中的N个元素,该元素均匀地隔开(大约N可能是偶数,数组长度可能是素数,等等),其中包括第一个arr[0]
元素和最后一个arr[len-1]
元素.
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.
示例:
>>> arr = np.arange(17)
>>> arr
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
然后,我想制作一个类似于以下的函数,以获取数组中均匀间隔的numElems
,该数组必须包含第一个和最后一个元素:
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
这有意义吗?
我已经尝试过arr[0:len:numElems]
(即使用数组start:stop:skip
表示法)和一些细微的变化,但是我在这里找不到想要的东西:
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])
或
>>> arr[0:len:numElems+1]
array([ 0, 5, 10, 15])
我并不在乎中间的元素是什么,只要它们均匀地间隔开一个1的索引就可以了.但是获取正确数量的元素(包括索引零和最后一个索引)至关重要.
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.
希望有人能帮助我快速找到一线客,谢谢!
Hopefully someone can help me find a quick one-liner, thanks!
推荐答案
要获取等间距索引的列表,请使用np.linspace
:
To get a list of evenly spaced indices, use np.linspace
:
idx = np.round(np.linspace(0, len(arr) - 1, numElems)).astype(int)
接下来,索引回到arr
以获取相应的值:
Next, index back into arr
to get the corresponding values:
arr[idx]
在强制转换为整数之前始终使用舍入.在内部,当提供dtype参数时,linspace
调用astype
.因此,此方法 NOT 等效于:
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屋!