Slicing at runtime

Question:

can someone explain me how to slice a numpy.array at runtime?
I don’t know the rank (number of dimensions) at ‘coding time’.

A minimal example:

import numpy as np
a = np.arange(16).reshape(4,4) # 2D matrix
targetsize = [2,3] # desired shape

b_correct = dynSlicing(a, targetsize)
b_wrong = np.resize(a, targetsize)

print a
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
print b_correct
[[0 1 2]
 [4 5 6]]
print b_wrong
[[0 1 2]
 [3 4 5]]

And my ugly dynSlicing():

def dynSlicing(data, targetsize):
    ndims = len(targetsize)

    if(ndims==1):
        return data[:targetsize[0]],
    elif(ndims==2):
        return data[:targetsize[0], :targetsize[1]]
    elif(ndims==3):
        return data[:targetsize[0], :targetsize[1], :targetsize[2]]
    elif(ndims==4):
        return data[:targetsize[0], :targetsize[1], :targetsize[2], :targetsize[3]]

Resize() will not do the job since it flats the array before dropping elements.

Thanks,
Tebas

Asked By: Tebas

||

Answers:

You can directly ‘change’ it. This is due to the nature of arrays only allowing backdrop.

Instead you can copy a section, or even better create a view of the desired shape:
Link

Answered By: Thomas Ahle

Passing a tuple of slice objects does the job:

def dynSlicing(data, targetsize):
    return data[tuple(slice(x) for x in targetsize)]
Answered By: fortran

Simple solution:

b = a[tuple(map(slice,targetsize))]
Answered By: Charles Beattie
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.