emm*_*ras 8 python numpy matrix
我有一个NumPy矩阵,我已经简化为例证:
a b c d e f
A = [[0, 1, 2, 3, 4, 5],
b [1, 0, 3, 4, 5, 6],
c [2, 3, 0, 5, 6, 7],
d [3, 4, 5, 0, 7, 8],
e [4, 5, 6, 7, 0, 9],
f [5, 6, 7, 8, 9, 0]]
Run Code Online (Sandbox Code Playgroud)
其中"十字路口"的数字很重要,但他们的顺序不对.我想重新排列行和列,以便新的顺序是[a,d,b,e,c,f]但是这个我称之为"交集"的值是相同的.
下面我开始按照我想要的方式转换矩阵.填充"e"行包括查看上面的交叉点(e,a)(= 4),然后(e,d)(= 7),然后(e,b)(= 5),(e,e) ,(e,c)和(e,f)
a d b e c f
A1= [[0, 3, 1, 4, 2, 5],
d [3, 0, 4, 7, 5, 8],
b [1, 4, 0, 5, 3, 6],
e [4, 7, 5,
Run Code Online (Sandbox Code Playgroud)
任何人都可以建议如何以这种方式重新安排我的矩阵?
And*_*ark 15
编辑:我偶然发现了一个使用高级索引的NumPy解决方案:
# a b c d e f
A = numpy.array([[0, 1, 2, 3, 4, 5],
[1, 0, 3, 4, 5, 6],
[2, 3, 0, 5, 6, 7],
[3, 4, 5, 0, 7, 8],
[4, 5, 6, 7, 0, 9],
[5, 6, 7, 8, 9, 0]])
# a d b e c f
new_order = [0, 3, 1, 4, 2, 5]
A1 = A[:, new_order][new_order]
Run Code Online (Sandbox Code Playgroud)
这是一个纯Python解决方案,可以转移到NumPy:
# a b c d e f
A = [[0, 1, 2, 3, 4, 5],
[1, 0, 3, 4, 5, 6],
[2, 3, 0, 5, 6, 7],
[3, 4, 5, 0, 7, 8],
[4, 5, 6, 7, 0, 9],
[5, 6, 7, 8, 9, 0]]
# a d b e c f
new_order = [0, 3, 1, 4, 2, 5] # maps previous index to new index
A1 = [[A[i][j] for j in new_order] for i in new_order]
Run Code Online (Sandbox Code Playgroud)
结果:
>>> pprint.pprint(A1)
[[0, 3, 1, 4, 2, 5],
[3, 0, 4, 7, 5, 8],
[1, 4, 0, 5, 3, 6],
[4, 7, 5, 0, 6, 9],
[2, 5, 3, 6, 0, 7],
[5, 8, 6, 9, 7, 0]]
Run Code Online (Sandbox Code Playgroud)
这是一个A适当修改的版本:
A[:] = [A[i] for i in new_order]
for row in A:
row[:] = [row[i] for i in new_order]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10996 次 |
| 最近记录: |