Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing at runtime

Tags:

python

numpy

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

like image 476
Tebas Avatar asked Dec 01 '25 01:12

Tebas


1 Answers

Passing a tuple of slice objects does the job:

def dynSlicing(data, targetsize):
    return data[tuple(slice(x) for x in targetsize)]
like image 159
fortran Avatar answered Dec 03 '25 17:12

fortran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!