Python矩阵转置方法大全

文章目录

  • 矩阵转置
    • 1、嵌套列表推导式
    • 2、numpy
    • 3、pandas
    • 4、zip
  • 降维
    • 列表推导式
    • numpy

矩阵转置

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()

Python矩阵转置方法大全_第1张图片

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]]

你可能感兴趣的:(Python实用技巧)