Python / numpy problem with array / vector with empty second dimension

I have what seems like an easy question.

Observe the code:

In : x=np.array([0, 6])
Out: array([0, 6])
In : x.shape
Out: (2L,)

      

Which shows that the array has no second dimension, so it x

doesn't differ from x.T

.

How to make x size (2L, 1L)? The real motivation for this question is that I have an array of a y

shape [3L,4L]

and I want y.sum (1) to be a vector transposed, etc.

+3


source to share


2 answers


As long as you can resize an array and add dimensions with [:,np.newaxis]

, you should be familiar with the most basic nested brackets, or list, notation. Note how it matches the display.

In [230]: np.array([[0],[6]])
Out[230]: 
array([[0],
       [6]])
In [231]: _.shape
Out[231]: (2, 1)

      

np.array

also takes a parameter ndmin

, although it adds extra dimensions at the beginning (default location for numpy

.)

In [232]: np.array([0,6],ndmin=2)
Out[232]: array([[0, 6]])
In [233]: _.shape
Out[233]: (1, 2)

      

The classic way to do something 2d is to change:

In [234]: y=np.arange(12).reshape(3,4)
In [235]: y
Out[235]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

      

sum

(and related functions) has a parameter keepdims

. Read the docs.

In [236]: y.sum(axis=1,keepdims=True)
Out[236]: 
array([[ 6],
       [22],
       [38]])
In [237]: _.shape
Out[237]: (3, 1)

      



empty 2nd dimension

- not quite terminology. More like a non-existent second dimension.

The dimension can have 0 members:

In [238]: np.ones((2,0))
Out[238]: array([], shape=(2, 0), dtype=float64)

      

If you are more familiar with MATLAB, which has at least 2d, you might like the subclass np.matrix

. It takes steps to ensure that most operations return a different 2d matrix:

In [247]: ym=np.matrix(y)
In [248]: ym.sum(axis=1)
Out[248]: 
matrix([[ 6],
        [22],
        [38]])

      

The matrix sum

does:

np.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)

      

The bit _collapse

allows you to return a scalar for ym.sum()

.

+4


source


One more point to save size information:



In [42]: X
Out[42]: 
array([[0, 0],
       [0, 1],
       [1, 0],
       [1, 1]])

In [43]: X[1].shape
Out[43]: (2,)

In [44]: X[1:2].shape
Out[44]: (1, 2)

In [45]: X[1]
Out[45]: array([0, 1])

In [46]: X[1:2]  # this way will keep dimension
Out[46]: array([[0, 1]])

      

+2


source







All Articles