简体   繁体   English

在Numpy中处理N个1矩阵

[英]Dealing with N by 1 matrices in Numpy

Given a numpy array of size (n,) how do you transform it to a numpy array of size (n,1) . 给定numpy数组(n,)如何将其转换为numpy数组(n,1)

The reason is because I am trying to matrix multiply to numpy arrays of size (n,) and (,n) to get a (n,n) but when I do: 原因是因为我试图将矩阵乘以大小(n,)(,n) numpy数组来得到a (n,n)但是当我这样做时:

numpy.dot(a,b.T)

It says that you can't do it. 它说你不能这样做。 I know as a fact that transposing a (n,) does nothing, so it would just be nice to change the (n,) and make them (n,1) and avoid this problem all together. 我知道事实上,转换a (n,)什么都不做,所以改变(n,)并使它们(n,1)并且完全避免这个问题就更好了。

You can use None for dimensions that you want to be treated as degenerate. 对于要将其视为简并的维,可以使用“ None ”。

a = np.asarray([1,2,3])
a[:]
a[:, None]

In [48]: a
Out[48]: array([1, 2, 3])

In [49]: a[:]
Out[49]: array([1, 2, 3])

In [50]: a[:, None]
Out[50]: 
array([[1],
       [2],
       [3]])

Use reshape (-1,1) to reshape (n,) to (n,1) , see detail examples: 使用reshape (-1,1)重塑(n,)(n,1) ,详见示例:

In [1]:

import numpy as np
A=np.random.random(10)
In [2]:

A.shape
Out[2]:
(10,)
In [3]:

A1=A.reshape(-1,1)
In [4]:

A1.shape
Out[4]:
(10, 1)
In [5]:

A.T
Out[5]:
array([ 0.6014423 ,  0.51400033,  0.95006413,  0.54321892,  0.2150995 ,
        0.09486603,  0.54560678,  0.58036358,  0.99914564,  0.09245124])
In [6]:

A1.T
Out[6]:
array([[ 0.6014423 ,  0.51400033,  0.95006413,  0.54321892,  0.2150995 ,
         0.09486603,  0.54560678,  0.58036358,  0.99914564,  0.09245124]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM