大家好,又见面了,我是你们的朋友全栈君。
文章目录
- 矩阵转置
-
- 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]]
代码语言:javascript复制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’)]
降维
列表推导式
代码语言:javascript复制ls = [[0, 1, 2], [3, 4, 5]]
print([j for i in ls for j in i])
[0, 1, 2, 3, 4, 5]
numpy
代码语言:javascript复制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))
代码语言:javascript复制[1 2 3 4 5 6]
[[1]
[2]
[3]
[4]
[5]
[6]]
[[1 2]
[3 4]
[5 6]]
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/136989.html原文链接:https://javaforall.cn