总的来说,交换行列索引+放到正确位置
python实现与分析
以下大部分代码都用于输出和分析思路,若需查看实现,请向下移至c++实现。
# 一些初始化和引入
import pandas as pd
col =["col", "row","value"]
matrix_dst1,matrix_dst2 = [],[]
from IPython.display import display
首先,初始化一个待转置的矩阵
matrix_src = [[1, 2, 12], [1, 3, 9], [3, 1, -3], [3, 6, 14], [4, 3, 24], [5, 2, 18], [6, 1, 15], [6, 4, -7]]
pd.DataFrame(matrix_src, columns=col)
col | row | value | |
---|---|---|---|
0 | 1 | 2 | 12 |
1 | 1 | 3 | 9 |
2 | 3 | 1 | -3 |
3 | 3 | 6 | 14 |
4 | 4 | 3 | 24 |
5 | 5 | 2 | 18 |
6 | 6 | 1 | 15 |
7 | 6 | 4 | -7 |
转置,无非就是把行列索引给交换就行了。转置过来以后是这样。
for item in matrix_src:
matrix_dst1.append([item[1],item[0],item[2]])
pd.DataFrame(matrix_dst1, columns=col)
col | row | value | |
---|---|---|---|
0 | 2 | 1< |