I have an n
-dimensional numpy array, and I'd like to get the i
-th slice of the k
-th dimension. There must be something better than
# ...
elif k == 5:
b = a[:, :, :, :, :, i, ...]
# ...
ndim to get the number of dimensions. Alternatively, we can use the shape attribute to get the size of each dimension and then use len() function for the number of dimensions. Use numpy. array() function to convert a list to a NumPy array and use one of the above two ways to get the number of dimensions.
Slice Two-dimensional Numpy Arrays To slice elements from two-dimensional arrays, you need to specify both a row index and a column index as [row_index, column_index] . For example, you can use the index [1,2] to query the element at the second row, third column in precip_2002_2013 .
The [:, :] stands for everything from the beginning to the end just like for lists. The difference is that the first : stands for first and the second : for the second dimension. a = numpy. zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])
b = a[(slice(None),) * k + (i,)]
Construct the indexing tuple manually.
As documented in the Python language reference, an expression of the form
a[:, :, :, :, :, i]
is converted to
a[(slice(None), slice(None), slice(None), slice(None), slice(None), i)]
We can achieve the same effect by building that tuple directly instead of using slicing notation. (There's the minor caveat that building the tuple directly produces a[(i,)]
instead of a[i]
for k=0
, but NumPy handles these the same for scalar i
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With