转置一维 NumPy 数组 [英] Transposing a 1D NumPy array

查看:66
本文介绍了转置一维 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,它基本上没有一维数组的概念.Matlab 的一维"数组是二维的.)

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天全站免登陆