Skip to content Skip to sidebar Skip to footer

What Is The Difference Between An Array With Shape (n,1) And One With Shape (n)? And How To Convert Between The Two?

Python newbie here coming from a MATLAB background. I have a 1 column array and I want to move that column into the first column of a 3 column array. With a MATLAB background this

Solution 1:

Several things are different. In numpy arrays may be 0d or 1d or higher. In MATLAB 2d is the smallest (and at one time the only dimensions). MATLAB readily expands dimensions the end because it is Fortran ordered. numpy, is by default c ordered, and most readily expands dimensions at the front.

In [1]: A = np.zeros([5,3])
In [2]: A[:,0].shape   
Out[2]: (5,)

Simple indexing reduces a dimension, regardless whether it's A[0,:] or A[:,0]. Contrast that with happens to a 3d MATLAB matrix, A(1,:,:) v A(:,:,1).

numpy does broadcasting, adjusting dimensions during operations like sum and assignment. One basic rule is that dimensions may be automatically expanded toward the start if needed:

In [3]: A[:,0] = np.ones(5)
In [4]: A[:,0] = np.ones([1,5])
In [5]: A[:,0] = np.ones([5,1])
...
ValueError: could not broadcast input array from shape (5,1) into shape (5)

It can change (5,) LHS to (1,5), but can't change it to (5,1).

Another broadcasting example, +:

In [6]: A[:,0] + np.ones(5);
In [7]: A[:,0] + np.ones([1,5]);
In [8]: A[:,0] + np.ones([5,1]);

Now the (5,) works with (5,1), but that's because it becomes (1,5), which together with (5,1) produces (5,5) - an outer product broadcasting:

In [9]: (A[:,0] + np.ones([5,1])).shape
Out[9]: (5, 5)

In Octave

>> x = ones(2,3,4);
>> size(x(1,:,:))
ans =
   134>> size(x(:,:,1))
ans =
   23>> size(x(:,1,1) )
ans =
   21>> size(x(1,1,:) )
ans =
   114

To do the assignment that you want you adjust either side

Index in a way that preserves the number of dimensions:

In [11]: A[:,[0]].shape    
Out[11]: (5, 1)
In [12]: A[:,[0]] = np.ones([5,1])

transpose the (5,1) to (1,5):

In [13]: A[:,0] = np.ones([5,1]).T

flatten/ravel the (5,1) to (5,):

In [14]: A[:,0] = np.ones([5,1]).flat
In [15]: A[:,0] = np.ones([5,1])[:,0]

squeeze, ravel also work.

Some quick tests in Octave indicate that it is more forgiving when it comes to dimensions mismatch. But the numpy prioritizes consistency. Once the broadcasting rules are understood, the behavior makes sense.

Post a Comment for "What Is The Difference Between An Array With Shape (n,1) And One With Shape (n)? And How To Convert Between The Two?"