Numpy数组中的“.T”是什么意思?

91 投票
3 回答
166016 浏览
提问于 2025-04-16 16:09

我在SciPy的文档中看到了这个例子:

x, y = np.random.multivariate_normal(mean, cov, 5000).T

这里最后的 .T 实际上是干什么的呢?

3 个回答

2

示例

import numpy as np
a = [[1, 2, 3]]
b = np.array(a).T  # ndarray.T The transposed array. [[1,2,3]] -> [[1][2][3]]
print("a=", a, "\nb=", b)
for i in range(3):
    print(" a=", a[0][i])  # prints  1 2 3
for i in range(3):
    print(" b=", b[i][0])  # prints  1 2 3 
14

.T 就是 np.transpose() 的意思。祝你好运!

97

这里的 .T 是用来获取一个对象的 T 属性,而这个属性恰好是一个 NumPy 数组。T 属性表示这个数组的转置,具体可以查看 文档

看起来你是在平面上生成随机坐标。multivariate_normal() 的输出可能是这样的:

>>> np.random.multivariate_normal([0, 0], [[1, 0], [0, 1]], 5)  
array([[ 0.59589335,  0.97741328],
       [-0.58597307,  0.56733234],
       [-0.69164572,  0.17840394],
       [-0.24992978, -2.57494471],
       [ 0.38896689,  0.82221377]])

这个矩阵的转置是:

array([[ 0.59589335, -0.58597307, -0.69164572, -0.24992978,  0.38896689],
       [ 0.97741328,  0.56733234,  0.17840394, -2.57494471,  0.82221377]])

我们可以通过序列解包方便地将其分成 xy 两部分。

撰写回答