python - How do I get a row of a 2d numpy array as 2d array -


how select row nxm numpy array array of size 1xm:

> import numpy > = numpy.array([[1,2], [3,4], [5,6]]) > array([[1, 2],        [3, 4],        [5, 6]]) > a.shape (e, 2) > a[0] array([1, 2]) > a[0].shape (2,) 

i'd

a[0].shape == (1,2) 

i'm doing because library want use seems require this.

if have of shape (2,) , want add new axis shape (1,2), easiest way use np.newaxis:

a = np.array([1,2])  a.shape #(2,)  b = a[np.newaxis, :]  print b #array([[1,2]])  b.shape #(1,2) 

if have of shape (n,2) , want slice same dimensionality slice shape (1,2), can use range of length 1 slice instead of 1 index:

a = np.array([[1,2], [3,4], [5,6]])  a[0:1] #array([[1, 2]])  a[0:1].shape #(1,2) 

another trick functions have keepdims option, example:

a #array([[1, 2], #       [3, 4], #       [5, 6]])  a.sum(1) #array([ 3,  7, 11])  a.sum(1, keepdims=true) #array([[ 3], #       [ 7], #       [11]]) 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -