如何根据 numpy 中向量的重新排序对 2D 矩阵轴进行重新排序
How to reorder 2D matrix axes based on reordering of a vector in numpy
我有一个2D ndarray
,形状是(n_x, n_t)
2D 矩阵沿其行(对于每一行都是水平的)存储一个量 Q
,因此 t
函数的离散版本,固定 x
。
在它的列中,对于固定的 t
,(即向下一个固定的列),2D 矩阵为不同的 x
保存该数量的 Q
值,所以我有一个离散版本Q(x)
.
我将把这个矩阵绘制成二维热图。
我有一个向量形状 (n_t, )
,其中包含二维矩阵存储数量 Q
的值的时间,对于任何给定的 x 值。因此,对于每一行,跨列,二维矩阵中这些值的基础时间是相同的。
在视觉上,对于 n_x=3
和 n_t=3
:
[
[Q_{11}, Q_{12}, Q_{13}],
[Q_{21}, Q_{22}, Q_{23}],
[Q_{31}, Q_{32}, Q_{33}]
]
行 [Q11, Q12, Q13]
基本上是 Q(x_1, ts)
,行 [Q21, Q22, Q23]
基本上是 Q(x_2, ts)
最后一行也是如此。
我有 ts
作为:[t1, t2, t3]
.
问题:
我将 ts
(无论出于何种原因)重新排序为 [t2, t3, t1]
。
我想将矩阵重新排序为:
[
[Q_{12}, Q_{13}, Q_{11}],
[Q_{22}, Q_{23}, Q_{21}],
[Q_{31}, Q_{33}, Q_{32}]
]
我该怎么做?我应该读些什么?
ts
向量的重新排序来自:np.fft.fftshift(np.fft.fftreq(ts))
.
谢谢!
根据评论编辑:
a = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
ts = np.array([100, 200, 300])
tss = np.array([200, 300, 100])
aa = np.array([
[2, 3, 1],
[5, 6, 4],
[8, 9, 7]
])
使用:
import numpy as np
a = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
ts = np.array([100, 200, 300])
tss = np.array([200, 300, 100])
# number of rows n_x in the original question
n_x = a.shape[0]
# find the original positions
indices = (ts == tss[:, None]).argmax(1)
res = np.take_along_axis(a, np.tile(indices, (n_x, 1)), axis=1)
print(res)
输出
[[2 3 1]
[5 6 4]
[8 9 7]]
我有一个2D ndarray
,形状是(n_x, n_t)
2D 矩阵沿其行(对于每一行都是水平的)存储一个量 Q
,因此 t
函数的离散版本,固定 x
。
在它的列中,对于固定的 t
,(即向下一个固定的列),2D 矩阵为不同的 x
保存该数量的 Q
值,所以我有一个离散版本Q(x)
.
我将把这个矩阵绘制成二维热图。
我有一个向量形状 (n_t, )
,其中包含二维矩阵存储数量 Q
的值的时间,对于任何给定的 x 值。因此,对于每一行,跨列,二维矩阵中这些值的基础时间是相同的。
在视觉上,对于 n_x=3
和 n_t=3
:
[
[Q_{11}, Q_{12}, Q_{13}],
[Q_{21}, Q_{22}, Q_{23}],
[Q_{31}, Q_{32}, Q_{33}]
]
行 [Q11, Q12, Q13]
基本上是 Q(x_1, ts)
,行 [Q21, Q22, Q23]
基本上是 Q(x_2, ts)
最后一行也是如此。
我有 ts
作为:[t1, t2, t3]
.
问题:
我将 ts
(无论出于何种原因)重新排序为 [t2, t3, t1]
。
我想将矩阵重新排序为:
[
[Q_{12}, Q_{13}, Q_{11}],
[Q_{22}, Q_{23}, Q_{21}],
[Q_{31}, Q_{33}, Q_{32}]
]
我该怎么做?我应该读些什么?
ts
向量的重新排序来自:np.fft.fftshift(np.fft.fftreq(ts))
.
谢谢!
根据评论编辑:
a = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
ts = np.array([100, 200, 300])
tss = np.array([200, 300, 100])
aa = np.array([
[2, 3, 1],
[5, 6, 4],
[8, 9, 7]
])
使用:
import numpy as np
a = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
ts = np.array([100, 200, 300])
tss = np.array([200, 300, 100])
# number of rows n_x in the original question
n_x = a.shape[0]
# find the original positions
indices = (ts == tss[:, None]).argmax(1)
res = np.take_along_axis(a, np.tile(indices, (n_x, 1)), axis=1)
print(res)
输出
[[2 3 1]
[5 6 4]
[8 9 7]]