2024-04-26 08:10:31 发布
网友
我想知道是否有一种方法,它索引/切片一个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]]
关于如何通过切片/索引实现这一点的想法?你知道吗
给出:
>>> 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]])
通过一些巧妙的重塑并不是那么困难:)
test.reshape((4, 4))[:, :2].reshape((2, 4))
给出:
你可以做:
它甚至适用于不同形状的初始阵列:
工作原理:
通过一些巧妙的重塑并不是那么困难:)
相关问题 更多 >
编程相关推荐