[Numpy-discussion] Slicing, sum, etc. reduces rank of array?

josef.pktd@gmai... josef.pktd@gmai...
Fri Sep 24 21:31:48 CDT 2010

```On Fri, Sep 24, 2010 at 10:23 PM, Benjamin Root <ben.root@ou.edu> wrote:
> On Fri, Sep 24, 2010 at 8:56 PM, George <gburdell1@gmail.com> wrote:
>>
>> I couldn't find an answer to my newbie question, so I'm posting it here.
>>
>> I have:
>>
>> a=numpy.array([[1,2],[3,4]])
>> b=numpy.array([[5,6],[7,8]])
>>
>> Via broadcasting, I know that
>> a*[[5],[7]]=numpy.array([[5,10],[21,28]])
>>
>> Being a recent convert from MATLAB, I expected the same result from
>> a*b[:,0],
>> assuming b[:,0] would be the column vector [[5],[7]].
>>
>> Unfortunately, I was wrong. b[:,0] is apparently a 1-rank array of shape
>> (2,).
>> This causes a*b[:,0] to evaluate as
>> a*numpy.array([[5,7]])=numpy.array([[5,14],[15,28]]) instead of
>> a*numpy.array([[5],[7]])
>>
>> To get the result I desire, the only way I've been able to come up with is
>>
>> a*b[:,0].reshape(2,1)
>>
>> to "coerce" b[:,0] into a column vector. Is there an easier way to do
>> this,
>> without having to do the reshape?
>>
>> I find similar things happen when I use other operations (e.g. "sum") that
>> also
>> seem to reduce the array rank.
>>
>> For example, I would expect numpy.sum(b,1) to also be a "column vector,"
>> but it
>> also evaluates to a 1-rank array [11, 15] with shape (2,)
>>
>> Any thoughts, suggestions?
>>
>
> This has bitten me several times in the past.  While there are some neat
> tricks around this issue, the one sure-fire, blunt-object solution to the
> problem is the np.atleast_2d() function.  There is also a 1d and 3d variant
> (although the 3d variant messes around a bit with the order of the axes...).

np.atleast_2d() leaves you with a row vector

my preferred generic version since I found it,, has been

np.expand_dims(a.sum(axis), axis)

special solution for given axis

b[:,0:1]  slice instead of index

b[:,0][:,None]  add axis back in

I managed to get used to it, finally, but None is almost the most
frequent index in numpy (maybe 3rd place)

Josef

>
> I will leave the more elegant solutions to others to give.
>
> Ben Root
>
>>
>> _______________________________________________
>> NumPy-Discussion mailing list
>> NumPy-Discussion@scipy.org
>> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>
```