Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent ":" in numpy [duplicate]

Tags:

python

numpy

I want to slice a multidimensional ndarray but don't know which dimension I will slice on. Lets say we have a ndarray A with shape (6,7,8). Sometimes I need to slice on 1st dimension A[:,3,4], sometimes on third A[1,2,:].

Is there any symbol represent the ":"? I want to use it to generate an index array.

index=np.zeros(3)
index[0]=np.:
index[1]=3
index[2]=4
A[index]
like image 214
Bo Shi Avatar asked Sep 01 '25 18:09

Bo Shi


1 Answers

The : slice can be explicitly created by calling slice(None) Here's a short example:

import numpy as np
A = np.arange(9).reshape(3, -1)

# extract the 2nd column
A[:, 1]

# equivalently we can do
cslice = slice(None) # represents the colon
A[cslice, 1]
like image 93
cel Avatar answered Sep 04 '25 08:09

cel