Python矩阵转置方法大全

矩阵转置

1、嵌套列表推导式

不会改变数据类型

matric = [[2, 2, 8],
          [0, 4, 0]]
transpose = [[matric[j][i] for j in range(len(matric))] for i in range(len(matric[0]))]
print(transpose)

[[2, 0],
 [2, 4],
 [8, 0]]

2、numpy

数据类型可能改变

import numpy as np
ls_of_ls = [[1, 1], [2, 2]]
ndarray = np.transpose(ls_of_ls)
print(ndarray)

[[1 2]
 [1 2]]

import numpy as np
ls_of_ls = [['a', 'b'], [3, 4]]
matrix = np.matrix(ls_of_ls)
print(matrix.T)

[[‘a’ ‘3’]
 [‘b’ ‘4’]]

3、pandas

数据类型可能改变

import pandas as pd
ls_of_ls = [[2, 'a'], [4, 'b']]
df = pd.DataFrame(ls_of_ls, columns=['A', 'B'])
print(df)
df.info()
print()
print(df.T)  # df.transpose()
df.T.info()

4、zip

转置后变为元组

ls = [[1, 2], ['a', 'b']]
print(list(zip(*ls)))

[(1, ‘a’),
 (2, ‘b’)]

降维

列表推导式

ls = [[0, 1, 2], [3, 4, 5]]
print([j for i in ls for j in i])

[0, 1, 2, 3, 4, 5]

numpy

import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.reshape(-1))  # 等价于:np.reshape(a, -1)
print()
print(a.reshape(-1, 1))  # 等价于:np.reshape(a, (-1, 1))
print()
print(a.reshape(3, 2))  # 等价于:np.reshape(a, (3, 2))
[1 2 3 4 5 6]

[[1]
 [2]
 [3]
 [4]
 [5]
 [6]]

[[1 2]
 [3 4]
 [5 6]]
  • 8
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小基基o_O

您的鼓励是我创作的巨大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值