python - Row vs. Column Vector Return during Numpy Array Slicing -
i learning python , stumbled across result confused me little bit when performing basic array slicing commands.
i created 4x5 matrix using command:
>>> = numpy.arange(20).reshape(4,5)
which gives:
[[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10,11,12,13,14], [15,16,17,18,19]]
if index array this:
>>> a[0:3, 2]
i row vector:
[2, 7, 12]
but if index array this:
>>> a[0:3, 2:3]
i column vector:
[[ 2], [ 7], [12]]
when plugging 2 commands in expected results same, why getting different types of vectors?
thank you!
tl;dr version
in numpy, taking single index along dimension array reduces dimensionality 1, taking index 2d array results in 1d array (first case). taken slice along dimension maintains same dimensionality, if slice has length of one, taking length-1 slice of 2d array still 2d array (second case)
detailed version
the issue first result isn't row vector, 1d array. when take single scalar index dimension, reduces number of dimensions 1. taking scalar index 4d array makes 3d array, taking 1 3d array makes 2d array, 2d array 1d array, , 1d array scalar.
this consistency sake. if taking item 1d array makes scalar (reduces dimensionality one), extension higher-dimensional equivalent operation should behave in equivalent way.
in second case, taking slice, not scalar. when that, keeps number of dimensions. taking slice of 2d array 2d array, if slice empty (or length 1 in case). consistency. if length-3 slice of 2d array 2d array, , length-2 slice of 2d array 2d array, length-1 slice of 2d array should 2d array.
this convenient convention, since allows explicitly define in couple of characters whether want reduce dimensionality or not.
some languages, matlab, don't have concept of 1d array (or, technically, matrix), arrays can 0d (scalars), 2d, 3d, etc., not 1d. python, on other hand, allows true 1d arrays, can trip people aren't used it.
Comments
Post a Comment