use*_*193 5 python arrays numpy reshape
好的我是(非常)新手Python用户,但我试图将一段Python代码翻译成R,我遇到了一个令人困惑的问题,即数组重塑.
让我们做一些示例数据:
X1 = np.array([[-0.047, -0.113, 0.155, 0.001],
[0.039, 0.254, 0.054, 0.201]], dtype=float)
In:X1
Out:
array([[-0.047, -0.113, 0.155, 0.001],
[0.039, 0.254, 0.054, 0.201]])
In:X1.shape
Out: (2,4)
Run Code Online (Sandbox Code Playgroud)
好的,我已经制作了一个包含2行和4列的2D数组.我很高兴.这行代码产生了混乱:
X2 = X1.reshape((2, -1, 1))
In: X2
Out:
array([[[-0.047],
[-0.113],
[0.155],
[0.001]],
[0.039],
[0.254],
[0.054],
[0.201]]])
In: X2.shape
Out: (2, 4, 1)
Run Code Online (Sandbox Code Playgroud)
所以我知道我添加了一个额外的维度(我认为是1reshape命令中的第三个数字),但我不明白这是做了什么的.形状意味着它仍然有2行4列,但显然还有其他东西被改变了.我的动机再一次是在R中做同样的操作,但直到我知道我明白我在这里转变了什么我才被困住了.(请原谅我,如果这是一个非常糟糕的问题我昨天才开始使用Python!)
通过reshape(2, -1, 1)你没有添加添加新的维度.你说过
* the 1st dimension should be of size 2
* the 3rd dimension should be of size 1
* the 2nd should be whatever remains
Run Code Online (Sandbox Code Playgroud)
所以,如果4.如果你只是想一个新的维度添加到现有的矩阵,你应该做的事情一样,唯一有效的选项x[:, np.newaxis, :](确切的使用取决于你想要的输出格式为)