In numpy what is the multidimensional equivalent of take

I have this bit of code

def build_tree_base(blocks, x, y, z): indicies = [ (x ,z ,y ), (x ,z+1,y ), (x ,z ,y+1), (x ,z+1,y+1), (x+1,z ,y ), (x+1,z+1,y ), (x+1,z ,y+1), (x+1,z+1,y+1), ] children = [blocks[i] for i in indicies] return Node(children=children) 

If the blocks are a three-dimensional numpy array.

What I would like to do is to replace the list comprehension with something like numpy.take, however, it seems that this applies only to unit dimension indices. Is there something like this that will work with multidimensional indexes?

I also know that you can do this with transpose, cut, and then change, but it was slow, so I'm looking for the best option.

+4
source share
2 answers

How about taking a 2x2x2 fragment then flat ?

 import numpy as np blocks = np.arange(2*3*4.).reshape((2,3,4)) i,j,k = 0,1,2 print [x for x in blocks[i:i+2, j:j+2, k:k+2].flat] 

( flat is an iterator, extend it this way either with np.fromiter() , or let Node on it.)

+1
source

Indexing by number makes this pretty simple ... You should be able to do something like this:

 def build_tree_base(blocks, x, y, z): idx = [x, x, x, x, x+1, x+1, x+1, x+1] idz = [z, z+1, z, z+1, z, z+1, z, z+1] idy = [y, y, y+1, y+1, y, y, y+1, y+1] children = blocks[idx, idz, idy] return Node(children=children) 

Edit: I have to point out that this (or any other β€œfancy” indexing ) will return a copy, not a view, to the original array ...

+2
source

All Articles