Python numpy: Dimension [0] in vectors (n-dim) vs. arrays (nxn-dim) -


i'm wondering how numpy array behaves. feel dimensions not consistent vectors (nx1 dimensional) 'real arrays' (nxn dimensional).

i dont get, why isn't working:

a = array(([1,2],[3,4],[5,6])) concatenate((a[:,0],a[:,1:]), axis = 1) # valueerror: input arrays must have same number of dimensions 

it seems : (at 1:]) makes difference, (:0 not working)

thanks in advance!

detailled version: expect shape(b)[0] references vertical direction in (nx1 arrays), in 2d (nxn) array. seems dimension [0] horizontal direction in arrays (nx1 arrays)?

from numpy import *  = array(([1,2],[3,4],[5,6])) b = a[:,0] print shape(a)  # (3l, 2l), [0] vertical print         # [1,2],[3,4],[5,6] print shape(b)  # (3l, ), [0] horizontal print b         # [1 3 5]  c = b * ones((shape(b)[0],1))  print shape(c)  # (3l, 3l), i'd expect (3l, 1l) print c         # [[ 1.  3.  5.], [ 1.  3.  5.], [ 1.  3.  5.]] 

what did wrong? there nicer way than

d = b * ones((1, shape(b)[0])) d = transpose(d) print shape(d)  # (3l, 1l) print d         # [[ 1.], [ 3.], [ 5.]] 

to (nx1) vector expect or want?

there 2 overall issues here. first, b not (n, 1) shaped array, (n,) shaped array. in numpy, 1d , 2d arrays different things. 1d arrays have no direction. vertical vs. horizontal, rows vs. columns, these 2d concepts.

the second has called "broadcasting". in numpy arrays, able broadcast lower-dimensional arrays higher-dimensional ones, , lower-dimensional part applied elementwise higher-dimensional one.

the broadcasting rules pretty simple:

when operating on 2 arrays, numpy compares shapes element-wise. starts trailing dimensions, , works way forward. 2 dimensions compatible when

they equal, or

one of them 1

in case, starts last dimension of ones((shape(b)[0],1)), 1. meets second criteria. multiplies array b elementwise each element of ones((shape(b)[0],1)), resulting in 3d array.

so equivalent to:

c = np.array([x*b x in ones(shape(b))]) 

edit:

to answer original question, want keep both first , second arrays 2d arrays.

numpy has simple rule this: indexing reduces number of dimensions, slicing doesn't. need have length-1 slice. in example, change a[:,0] a[:,:1]. means 'get every column second one'. of course includes first column, still considered slice operation rather getting element, still preservers number of dimensions:

>>> print(a[:, 0]) [1 3 5] >>> print(a[:, 0].shape) (3,) >>> print(a[:, :1]) [[1]  [3]  [5]] >>> print(a[:, :1].shape) (3, 1) >>> print(concatenate((a[:,:1],a[:,1:]), axis = 1)) [[1 2]  [3 4]  [5 6]] 

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -