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
JavaScript
x
7
1
# X View
2
my_view = [10, :, :]
3
# Y View
4
# my_view = [:, 4, :]
5
# Z View
6
# my_view = [:, :, 7]
7
and choose which view to run in my script.
Then the rest of my code can apply the myview slice when visualizing,
JavaScript
1
3
1
plt.plot(my_data[myview])
2
plt.plot(more_data[myview])
3
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:
JavaScript
1
3
1
In [21]: np.s_[10,:,:]
2
Out[21]: (10, slice(None, None, None), slice(None, None, None))
3
but you can create that directly:
JavaScript
1
3
1
In [22]: (10,slice(None),slice(None))
2
Out[22]: (10, slice(None, None, None), slice(None, None, None))
3
arr[i,j]
is the same as arr[(i,j)]
, the comma creates a tuple.
JavaScript
1
3
1
In [23]: 10,slice(None),slice(None)
2
Out[23]: (10, slice(None, None, None), slice(None, None, None))
3
You can create a more general indexing tuple this way.