一维数组的 Numpy 转置未给出预期结果 [英] Numpy transpose of 1D array not giving expected result

查看:62
本文介绍了一维数组的 Numpy 转置未给出预期结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Python scipy 模块中为 transpose() 方法尝试一个非常基本的示例,但它没有给出预期的结果.我在 pylab 模式下使用 Ipython.

I am trying a very basic example in Python scipy module for transpose() method but it's not giving expected result. I am using Ipython with pylab mode.

a = array([1,2,3]
print a.shape
>> (3,)

b = a.transpose()
print b.shape
>> (3,)

如果我打印数组a"的内容和b",它们是相似的.

If I print the contents of arrays "a" and "b", they are similar.

期望是:(这将导致 Matlab 转置)

Expectation is: (which will be result in Matlab on transpose)

 [1,
  2,
  3]

推荐答案

NumPy 的 transpose() 有效地反转了数组的形状.如果数组是一维的,这意味着它没有效果.

NumPy's transpose() effectively reverses the shape of an array. If the array is one-dimensional, this means it has no effect.

在 NumPy 中,数组

In NumPy, the arrays

array([1, 2, 3])

array([1,
       2,
       3])

实际上是相同的——它们只是在空格上有所不同.您可能想要的是相应的二维数组,对于它们 transpose() 可以正常工作.还可以考虑使用 NumPy 的 matrix 类型:

are actually the same – they only differ in whitespace. What you probably want are the corresponding two-dimensional arrays, for which transpose() would work fine. Also consider using NumPy's matrix type:

In [1]: numpy.matrix([1, 2, 3])
Out[1]: matrix([[1, 2, 3]])

In [2]: numpy.matrix([1, 2, 3]).T
Out[2]: 
matrix([[1],
        [2],
        [3]])

请注意,对于大多数应用程序,普通的一维数组既可以用作行向量也可以用作列向量,但是当来自 Matlab 时,您可能更喜欢使用 numpy.matrix.

Note that for most applications, the plain one-dimensional array would work fine as both a row or column vector, but when coming from Matlab, you might prefer using numpy.matrix.

这篇关于一维数组的 Numpy 转置未给出预期结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆