0

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?

1
  • myview=(4, slice(None), slice(None)) etc Commented Dec 7, 2021 at 10:50

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.