Numpy 索引,获取宽度为 2 的波段
Posted
技术标签:
【中文标题】Numpy 索引,获取宽度为 2 的波段【英文标题】:Numpy index, get bands of width 2 【发布时间】:2015-11-17 06:37:25 【问题描述】:我想知道是否有一种方法可以索引/切片一个 numpy 数组,这样就可以得到每隔一个带 2 个元素。换句话说,给定:
test = np.array([[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16]])
我想得到数组:
[[1, 2, 5, 6],
[9, 10, 13, 14]]
关于如何通过切片/索引来实现这一点的想法?
【问题讨论】:
【参考方案1】:通过一些智能重塑并不难 :)
test.reshape((4, 4))[:, :2].reshape((2, 4))
【讨论】:
【参考方案2】:给定:
>>> test
array([[ 1, 2, 3, 4, 5, 6, 7, 8],
[ 9, 10, 11, 12, 13, 14, 15, 16]])
你可以这样做:
>>> test.reshape(-1,2)[::2].reshape(-1,4)
array([[ 1, 2, 5, 6],
[ 9, 10, 13, 14]])
这甚至适用于不同形状的初始数组:
>>> test2
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
>>> test2.reshape(-1,2)[::2].reshape(-1,4)
array([[ 1, 2, 5, 6],
[ 9, 10, 13, 14]])
>>> test3
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
>>> test3.reshape(-1,2)[::2].reshape(-1,4)
array([[ 1, 2, 5, 6],
[ 9, 10, 13, 14]])
它是如何工作的:
1. Reshape into two columns by however many rows:
>>> test.reshape(-1,2)
array([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10],
[11, 12],
[13, 14],
[15, 16]])
2. Stride the array by stepping every second element
>>> test.reshape(-1,2)[::2]
array([[ 1, 2],
[ 5, 6],
[ 9, 10],
[13, 14]])
3. Set the shape you want of 4 columns, however many rows:
>>> test.reshape(-1,2)[::2].reshape(-1,4)
array([[ 1, 2, 5, 6],
[ 9, 10, 13, 14]])
【讨论】:
以上是关于Numpy 索引,获取宽度为 2 的波段的主要内容,如果未能解决你的问题,请参考以下文章