Python: Index an array using the colon operator in an arbitrary dimension

后端 未结 2 960
暖寄归人
暖寄归人 2021-02-20 02:17

I have a numpy nd array. A simplified version of my task is to take a vector from along each axis. To illustrate:

import numpy
x = numpy.array(range(24)).reshape         


        
2条回答
  •  伪装坚强ぢ
    2021-02-20 02:47

    You could compose an string with the code selecting the dimension you want and use eval to execute that code string.

    An start is:

    n = 2
    sel = "0,"*(n-1) + ":"
    eval('x[' + sel + ']')
    

    To get exactly what you want, thinks are a little bit more complicated (but not so much):

    ind = 2
    n = 3
    sel = "".join([ ("0" if i != ind else ":") + ("," if i < n-1 else "") for i in xrange(n)])
    eval('x[' + sel + ']')
    

    It is the same strategy that is used for Dynamic SQL.

提交回复
热议问题