Skip to content
Advertisement

Store slice of 3D Numpy Array as a variable

I’ve got various 3D arrays that I’m viewing 2D slices of, along either the X, Y or Z axis.

To simplify my code, I would like to have one location of declaring the slice such as

# X View
my_view = [10, :, :] 
# Y View
# my_view = [:, 4, :] 
# Z View
# my_view = [:, :, 7]

and choose which view to run in my script.

Then the rest of my code can apply the myview slice when visualizing,

plt.plot(my_data[myview])
plt.plot(more_data[myview])

There’s no way to “store” the ‘:’ portion of the slice. How would I accomplish this in Python/Numpy?

Advertisement

Answer

np.s_ is a handy tool for making an indexing tuple:

In [21]: np.s_[10,:,:]
Out[21]: (10, slice(None, None, None), slice(None, None, None))

but you can create that directly:

In [22]: (10,slice(None),slice(None))
Out[22]: (10, slice(None, None, None), slice(None, None, None))

arr[i,j] is the same as arr[(i,j)], the comma creates a tuple.

In [23]: 10,slice(None),slice(None)
Out[23]: (10, slice(None, None, None), slice(None, None, None))

You can create a more general indexing tuple this way.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement