简体   繁体   English

Python-NumPy切片每行不同

[英]Python-NumPy slice differently each line

I have a small problem, as I am learning Python. 我在学习Python时遇到一个小问题。 I am trying to slice a 2D-array in a particular way : taking one item over two, but at each line we begin at a different index, for example if we have a = np.reshape(np.arange(16),(4,4)) , so 我正在尝试以一种特殊的方式对2D数组进行切片:将一项超过两项,但在每一行我们都从一个不同的索引开始,例如,如果我们有a = np.reshape(np.arange(16),(4,4)) ,所以

>>print(a) = [[ 0  1  2  3]
              [ 4  5  6  7]
              [ 8  9 10 11]
              [12 13 14 15]] 

We would like to end with 我们想以

>>print(new_a) = [[ 0  2]
                  [ 5  7]
                  [ 8 10]
                  [13 15]]

I am sure that it is not too complicated, but I couldn't find the answer :( (I now how to slice a np-array, just not how to change each row) 我确信它并不太复杂,但是我找不到答案:(((我现在如何切片np数组,只是没有如何更改每一行)

Thank you and have a nice day ! 谢谢你,祝你有美好的一天 !

As long as the dimensions of a are even, one can get this specific (checkerboard) pattern with np.einsum : 只要a的尺寸是均匀的,就可以使用np.einsum来获得这种特定的(棋盘)模式:

>>> np.einsum('jiki->jik', a.reshape(2, 2, 2, 2)).reshape(4, 2)
array([[ 0,  2],
       [ 5,  7],
       [ 8, 10],
       [13, 15]])

or, more generally 或更一般地

>>> a = np.arange(40).reshape(4, 10)
>>> np.einsum('jiki->jik', a.reshape(a.shape[0]//2, 2, -1, 2)).reshape(a.shape[0], -1)
array([[ 0,  2,  4,  6,  8],
       [11, 13, 15, 17, 19],
       [20, 22, 24, 26, 28],
       [31, 33, 35, 37, 39]])

You can use slicing with steps . 您可以将切片与step一起使用。 Do this from 0 and from 1 with step size 2. This will give you two separate arrays, you can then do the work and join them back. 从0开始,从1开始,步长为2。这将为您提供两个单独的数组,然后您可以进行工作并将它们重新结合在一起。

I am pretty new to numpy so there may be a better approach. 我对numpy很陌生,因此可能有更好的方法。

b = a.take([0,2,5,7,8,10,13,15]).reshape(4,2)
print(b)

array([[ 0,  2],
       [ 5,  7],
       [ 8, 10],
       [13, 15]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM