Home > Enterprise >  Store slice of 3D Numpy Array as a variable
Store slice of 3D Numpy Array as a variable

Time:12-08

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?

CodePudding user response:

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.

CodePudding user response:

Why not make my_view a function?

def my_view(arr):
    """Returns a certain 2d slice of a 3d NumPy array."""
    # X View
    return arr[10, :, :] 
    # Y View
    # return arr[:, 4, :] 
    # Z View
    # return arr[:, :, 7]

Application:

plt.plot(my_view(my_data))
plt.plot(my_view(more_data))
  • Related