在numpy中转置矩阵 [英] Transpose of a matrix in numpy

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

问题描述

我有这个numpy数组:

I have this numpy array:

a = np.array([[[1,2,3],[-1,-2,-3]],[[4,5,6],[-4,-5,-6]]])

b a 的转置.我希望b像这样:

b is a transpose of a. I want b be like this:

b = np.array([[[1,-1],[2,-2],[3,-3]],[[4,-4],[5,-5],[6,-6]]])

可以一行完成吗?

如果我有这个,则:

a = np.empty(3,dtype = object)

a[0] = np.array([[1,2,3],[-1,-2,-3]])

a[1] = np.array([[4,5,6],[-4,-5,-6]])

我怎么得到b?

推荐答案

您可以使用 np.transpose(a,(0,2,1)):

In [26]: a = np.array([[[1,2,3],[-1,-2,-3]],[[4,5,6],[-4,-5,-6]]])

In [27]: b = np.transpose(a,(0,2,1))

In [28]: print a
[[[ 1  2  3]
  [-1 -2 -3]]

 [[ 4  5  6]
  [-4 -5 -6]]]

In [29]: print b
[[[ 1 -1]
  [ 2 -2]
  [ 3 -3]]

 [[ 4 -4]
  [ 5 -5]
  [ 6 -6]]]


对于带有 dtype = object 数组的已编辑问题,没有直接方法可以计算转置,因为numpy不知道如何转置通用对象.但是,您可以使用列表推导并分别转置每个对象:


For your edited question with an array of dtype=object -- there is no direct way to compute the transpose, because numpy doesn't know how to transpose a generic object. However, you can use list comprehension and transpose each object separately:

In [90]: a = np.empty(2,dtype = object)

In [91]: a[0] = np.array([[1,2,3],[-1,-2,-3]])

In [92]: a[1] = np.array([[4,5,6],[-4,-5,-6]])

In [93]: print a
[[[ 1  2  3]
 [-1 -2 -3]] [[ 4  5  6]
 [-4 -5 -6]]]

In [94]: b = np.array([np.transpose(o) for o in a],dtype=object)

In [95]: print b
[[[ 1 -1]
  [ 2 -2]
  [ 3 -3]]

 [[ 4 -4]
  [ 5 -5]
  [ 6 -6]]]

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

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