python - discriminate basic and advanced slicing of numpy array -


i'm reading doc numpy array indexing, still unclear how discriminate basic , advanced slicing.

thanks if explain bit.

x[(1,2,3),] fundamentally different x[(1,2,3)]. latter equivalent x[1,2,3] trigger basic selection while former trigger advanced indexing. sure understand why occurs.

also recognize x[[1,2,3]] trigger advanced indexing, whereas x[[1,2,slice(none)]]` trigger basic slicing.

start simple 1d array:

in [326]: x=np.arange(10) 

these 2 expressions same thing - select 3 elements array. verify return copy, x[1:4] returns view.

in [327]: x[(1,2,3),] out[327]: array([1, 2, 3])  in [328]: x[[1,2,3]] out[328]: array([1, 2, 3]) 

but without command, tuple raises error:

in [329]: x[(1,2,3)] ... indexerror: many indices array 

same as:

in [330]: x[1,2,3] indexerror: many indices array 

x[1,2,3] converted python interpreter call x.__getitem__((1,2,3)). is, input values passed tuple method. () in x[(1,2,3)] make no difference. comma in first expression adds layer of nesting:

in [338]: ((1,2,3)) out[338]: (1, 2, 3)  in [339]: ((1,2,3),) out[339]: ((1, 2, 3),) 

x[[1,2,slice(none)]] equivalent x[1,2,:], i'll have make 3d array verify this.

in [344]: x=np.arange(64).reshape(4,4,4) 

3d indexing of single element:

in [345]: x[(1,2,3)] out[345]: 27  in [346]: x[1,2,3] out[346]: 27 

3d, slice on last dimension:

in [347]: x[1,2,:] out[347]: array([24, 25, 26, 27]) 

the interpreter accepts : notation in square indexing brackets:

in [348]: x[(1,2,:)] ... syntaxerror: invalid syntax 

but slice can write tuple or list

in [349]: x[(1,2,slice(none))] out[349]: array([24, 25, 26, 27])  in [350]: x[[1,2,slice(none)]] out[350]: array([24, 25, 26, 27]) 

tuple works here same reason did (1,2,3). think treating [] case same way because that's thing makes sense. combining numbers slice make advanced index not make sense.

there indexing trick lets me pick 2 items plus slice:

in [354]: x[np.r_[1,3, 6:10]] out[354]: array([1, 3, 6, 7, 8, 9]) 

but expanding slice range

in [353]: np.r_[1,3, 6:10] out[353]: array([1, 3, 6, 7, 8, 9]) 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -