简体   繁体   中英

Looking to loop over difference numpy array slicings

I have a multi dimensional numpy array where i am looking to take different slicings from like this:

A=Array[1,:,:,:,:]
B=Array[:,1,:,:,:]
C=Array[:,:,1,:,:]
D=Array[:,:,:,1,:]
E=Array[:,:,:,:,1]

I then need to process these in the exact same way so i thought about doing it in a simple loop. However i do not know how to do this.

I thought about list comprehension like:

for i in range(5):
   Sliced=Array[1 if x==i else : for x in range(5)]

but this obviously does not work.

When you write Array[x,y,z] you are actually passing a tuple (x,y,z) into the brackets [...] , while a:b:c constructs within there are syntax sugar for slice(a, b, c) with None in place of unspecified values (eg ::2 is slice(None, None, 2) ). So what you mean should be obtained with something like this:

for i in range(5):
    Sliced = Array[tuple(1 if x==i else slice(None) for x in range(5))]

IIUC, one way would be to rotate the axis of array instead of index:

arr = np.random.random((2,3,4,5,6))

arrays = []
for i in range(arr.ndim):
    print(arr.shape)
    arrays.append(arr[1, ...])
    arr = np.moveaxis(arr, 0, -1)

Output for shape:

(2, 3, 4, 5, 6)
(3, 4, 5, 6, 2)
(4, 5, 6, 2, 3)
(5, 6, 2, 3, 4)
(6, 2, 3, 4, 5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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