[Numpy-discussion] How to Keep An Array Two Dimensional
Warren Weckesser
warren.weckesser@gmail....
Sun Nov 25 20:35:06 CST 2012
On Sun, Nov 25, 2012 at 8:24 PM, Tom Bennett <tom.bennett@mail.zyzhu.net>wrote:
> Hi,
>
> I am trying to extract n columns from an 2D array and then operate on the
> extracted columns. Below is the code:
>
> A is an MxN 2D array.
>
> u = A[:,:n] #extract the first n columns from A
>
> B = np.dot(u, u.T) #take outer product.
>
> This code works when n>1. However, when n=1, u becomes an 1D array instead
> of an Mx1 2D array and the code breaks down.
>
> I wonder if there is any way to keep u=A[:,:n] an Mxn array no matter what
> value n takes. I do not want to use matrix because array is more convenient
> in other places.
>
>
Tom,
Your example works for me:
In [1]: np.__version__
Out[1]: '1.6.2'
In [2]: A = arange(15).reshape(3,5)
In [3]: A
Out[3]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
In [4]: u = A[:,:1]
In [5]: u
Out[5]:
array([[ 0],
[ 5],
[10]])
In [6]: B = np.dot(u, u.T)
In [7]: B
Out[7]:
array([[ 0, 0, 0],
[ 0, 25, 50],
[ 0, 50, 100]])
Warren
> Thanks,
> Tom
>
>
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20121125/0a3a54a1/attachment.html
More information about the NumPy-Discussion
mailing list