python - 重新排列 numpy 数组的行和列(在单个操作中)

标签 python numpy indexing

首先让我们解决这个问题: 我已经知道这里讨论的解决方案:Create NumPy array from another array by specifying rows and columns

假设我有一个数组

test = np.arange(12).reshape((3,4))

array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

我想将其行和列重新排列为 test2

array([[ 1,  0,  3,  2],
       [ 9,  8, 11, 10],
       [ 5,  4,  7,  6]])

我现在使用的解决方案与上面链接中已经回答的解决方案相同:

test2 = test[[0,2,1]][:,[1,0,3,2]]

但是,此解决方案创建了不必要的数据中间副本:它首先创建仅包含打乱行的副本 test[[0,2,1]] ,然后创建第二个副本,其中也已打乱列。对于如此小的阵列,没有人关心,但如果阵列巨大,则该解决方案感觉不是最佳的。 numpy 是否允许行和列同时洗牌?看起来像 test[[0,2,1],[1,0,3,2]] 的东西,除了 numpy 不会那样解释这个操作......

最佳答案

是的,这就是 np.ix_ 的目的:

>>> test[np.ix_([0,2,1], [1,0,3,2])]
array([[ 1,  0,  3,  2],
       [ 9,  8, 11, 10],
       [ 5,  4,  7,  6]])

它仍然会根据两个输入数组创建一个中间索引数组,但不会对 test 数组进行两次索引。

请注意,np.ix_ 只是向索引数组添加维度,当您索引数组时,这些维度将被“广播”:

>>> np.ix_([0,2,1], [1,0,3,2])
(array([[0],
        [2],
        [1]]), array([[1, 0, 3, 2]]))

关于python - 重新排列 numpy 数组的行和列(在单个操作中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46045109/

相关文章:

python - 在 python 中准备一个返回矩阵有什么好处?

python - 如何将 np.array 中的符号更改为 sympy subs?

mysql - 索引数据会加快通过mysql搜索的速度吗?

c - 3 维数组表示

mysql 全文索引

python - 为什么 scikit-learn 的 RandomForestClassifier 在显式设置中不是确定性的?

python - 如何将视频流从一个 python 传递到另一个?

python - 为什么在 Python 中打印(5 ** 2 ** 0 ** 1)= 5?

python - 迭代结果集时的性能问题

python - 使用 matplotlib 绘制轮廓时出错