在周期性条件下切片numpy数组 [英] slicing numpy array in periodic conditions

查看:42
本文介绍了在周期性条件下切片numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在周期性条件下对 3x3 形状的 numpy 数组进行切片.

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]

结果是array([2, 3, 4, 5, 6, 7]).现在如果我需要从 7 切片到 5 ......

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

sub = a[7:5]

结果显然是array([], dtype=int32).但我需要的是 array([7,8,9,0,1,2,3,4])

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

有什么有效的方法吗?

推荐答案

同样,在周期性条件下进行滚动或切片或切片的一种简单好方法是使用模数和 numpy.reshape.例如

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]]])

假设我们需要对 [0:3, -1:1, 0:3] 进行切片,其中 3:1 是一个滚动切片.

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]]])

这篇关于在周期性条件下切片numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆