slicing numpy array in periodic conditions

感情迁移 提交于 2021-02-07 04:27:10

问题


how can I slice a 3x3 shape numpy array in periodic conditions.

for example, for simplicity its in one dimension:

import numpy as np
a = np.array(range(10))

if the slice is within the length of the array it is straightforward

sub = a[2:8]

the result is array([2, 3, 4, 5, 6, 7]). Now if I need to slice from 7 to 5 ...

sub = a[7:5]

the result is obviously array([], dtype=int32). But what I need is array([7,8,9,0,1,2,3,4])

Is there any efficient way to do so ?


回答1:


I think what you're looking for is: numpy.roll (http://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html)




回答2:


Likewise a good and easy way of doing a rolled or slicing or slicing in periodic conditions is by using the modulo and the numpy.reshape. for example

import numpy as np
a = np.random.random((3,3,3))
array([[[ 0.98869832,  0.56508155,  0.05431135],
        [ 0.59721238,  0.62269635,  0.78196073],
        [ 0.03046364,  0.25689747,  0.85072087]],

       [[ 0.63096169,  0.66061845,  0.88362948],
        [ 0.66854665,  0.02621923,  0.41399149],
        [ 0.72104873,  0.45633403,  0.81190428]],

       [[ 0.42368236,  0.11258298,  0.27987449],
        [ 0.65115635,  0.42433058,  0.051015  ],
        [ 0.60465148,  0.12601221,  0.46014229]]])

lets say we need to slice [0:3, -1:1, 0:3] where 3:1 is a rolled slice.

a[0:3, -1:1, 0:3]
array([], shape=(3, 0, 3), dtype=float64)

This is very normal. the solution is:

sl0 = np.array(range(0,3)).reshape(-1,1, 1)%a.shape[0]
sl1 = np.array(range(-1,1)).reshape(1,-1, 1)%a.shape[1]
sl2 = np.array(range(0,3)).reshape(1,1,-1)%a.shape[2]

a[sl0,sl1,sl2]
array([[[ 0.03046364,  0.25689747,  0.85072087],
        [ 0.98869832,  0.56508155,  0.05431135]],

       [[ 0.72104873,  0.45633403,  0.81190428],
        [ 0.63096169,  0.66061845,  0.88362948]],

       [[ 0.60465148,  0.12601221,  0.46014229],
        [ 0.42368236,  0.11258298,  0.27987449]]])


来源:https://stackoverflow.com/questions/15113181/slicing-numpy-array-in-periodic-conditions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!