简体   繁体   中英

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

How do I select a row from a NxM numpy array as an array of size 1xM:

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

I'd like

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

I'm doing this because a library I want to use seems to require this.

If you already have it, call .reshape() :

>>> a = numpy.array([[1, 2], [3, 4]])
>>> b = a[0]
>>> c = b.reshape((1, -1))
>>> c
array([[1, 2]])
>>> c.shape
(1, 2)

You can also use a range to keep the array two-dimensional in the first place:

>>> b = a[0:1]
>>> b
array([[1, 2]])
>>> b.shape
(1, 2)

Note that all of these will have the same backing store.

If you have something of shape (2,) and you want to add a new axis so that the shape is (1,2) , the easiest way is to 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 you have something of shape (N,2) and want to slice it with the same dimensionality to get a slice with shape (1,2) , then you can use a range of length 1 as your slice instead of one index:

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

a[0:1]
#array([[1, 2]])

a[0:1].shape
#(1,2)

Another trick is that some functions have a keepdims option, for 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]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM