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

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


While you can reshape arrays, 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]: _.shapeOut[231]: (2, 1)

np.array also takes a ndmin parameter, though it add extra dimensions at the start (the default location for numpy.)

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

A classic way of making something 2d - reshape:

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

sum (and related functions) has a keepdims parameter. Read the docs.

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

empty 2nd dimension isn't quite the terminology. More like a nonexistent 2nd dimension.

A dimension can have 0 terms:

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

If you are more familiar with MATLAB, which has a minimum of 2d, you might like the np.matrix subclass. It takes steps to ensure that most operations return another 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 _collapse bit lets it return a scalar for ym.sum().


There is another point to keep dimension info:

In [42]: XOut[42]: array([[0, 0],       [0, 1],       [1, 0],       [1, 1]])In [43]: X[1].shapeOut[43]: (2,)In [44]: X[1:2].shapeOut[44]: (1, 2)In [45]: X[1]Out[45]: array([0, 1])In [46]: X[1:2]  # this way will keep dimensionOut[46]: array([[0, 1]])