转置NumPy数组 [英] Transposing a NumPy array

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

问题描述

我使用Python和NumPy,并且在转置"方面遇到一些问题:

I use Python and NumPy and have some problems with "transpose":

import numpy as np
a = np.array([5,4])
print(a)
print(a.T)

调用a.T不会转置数组.例如,如果a[[],[]],则它可以正确转置,但是我需要[...,...,...]的转置.

Invoking a.T is not transposing the array. If a is for example [[],[]] then it transposes correctly, but I need the transpose of [...,...,...].

推荐答案

它完全按照预期的方式工作. 1D 数组的转置仍然是 1D 数组! (如果您习惯使用matlab,从根本上来说就没有1D数组的概念.Matlab的"1D"数组是2D.)

It's working exactly as it's supposed to. The transpose of a 1D array is still a 1D array! (If you're used to matlab, it fundamentally doesn't have a concept of a 1D array. Matlab's "1D" arrays are 2D.)

如果要将一维矢量转换为二维数组然后转置,只需用np.newaxis(或None,它们相同,newaxis更具可读性)将其切成薄片即可.

If you want to turn your 1D vector into a 2D array and then transpose it, just slice it with np.newaxis (or None, they're the same, newaxis is just more readable).

import numpy as np
a = np.array([5,4])[np.newaxis]
print(a)
print(a.T)

不过一般来说,您不必担心这一点.如果只是出于习惯,添加额外的维度通常不是您想要的.进行各种计算时,Numpy将自动广播一维数组.当您只想要一个向量时,通常无需区分行向量和列向量(都不是向量.它们都是二维的!).

Generally speaking though, you don't ever need to worry about this. Adding the extra dimension is usually not what you want, if you're just doing it out of habit. Numpy will automatically broadcast a 1D array when doing various calculations. There's usually no need to distinguish between a row vector and a column vector (neither of which are vectors. They're both 2D!) when you just want a vector.

这篇关于转置NumPy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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