重新排列 numpy 二维数组的列 [英] Rearrange columns of numpy 2D array

查看:42
本文介绍了重新排列 numpy 二维数组的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将 numpy 2D 数组中的列顺序更改为新的任意顺序?例如,我有一个数组

array([[10, 20, 30, 40, 50],[ 6, 7, 8, 9, 10]])

我想把它改成,比如说

array([[10, 30, 50, 40, 20],[ 6, 8, 10, 9, 7]])

通过应用排列

0 ->01 ->42 ->13 ->34 ->2

在列上.因此,在新矩阵中,我希望原始矩阵的第一列保持原位,第二列移动到最后一列,依此类推.

是否有一个 numpy 函数可以做到这一点?我有一个相当大的矩阵,并希望得到更大的矩阵,所以我需要一个解决方案,如果可能的话,它可以快速且适当地执行此操作(置换矩阵是不可行的)

谢谢.

解决方案

这在 O(n) 时间和 O(n) 空间中使用花式索引是可能的:

<预><代码>>>>将 numpy 导入为 np>>>a = np.array([[10, 20, 30, 40, 50],... [ 6, 7, 8, 9, 10]])>>>排列 = [0, 4, 1, 3, 2]>>>idx = np.empty_like(排列)>>>idx[permutation] = np.arange(len(permutation))>>>a[:, idx] # 返回一个重新排列的副本数组([[10, 30, 50, 40, 20],[ 6, 8, 10, 9, 7]])>>>a[:] = a[:, idx] # 就地修改 a

请注意,a[:, idx]返回副本,而不是视图.O(1) 空间解决方案在一般情况下是不可能的,因为 numpy 数组在内存中是如何跨步的.

Is there a way to change the order of the columns in a numpy 2D array to a new and arbitrary order? For example, I have an array

array([[10, 20, 30, 40, 50],
       [ 6,  7,  8,  9, 10]])

and I want to change it into, say

array([[10, 30, 50, 40, 20],
       [ 6,  8, 10,  9,  7]])

by applying the permutation

0 -> 0
1 -> 4
2 -> 1
3 -> 3
4 -> 2

on the columns. In the new matrix, I therefore want the first column of the original to stay in place, the second to move to the last column and so on.

Is there a numpy function to do it? I have a fairly large matrix and expect to get even larger ones, so I need a solution that does this quickly and in place if possible (permutation matrices are a no-go)

Thank you.

解决方案

This is possible in O(n) time and O(n) space using fancy indexing:

>>> import numpy as np
>>> a = np.array([[10, 20, 30, 40, 50],
...               [ 6,  7,  8,  9, 10]])
>>> permutation = [0, 4, 1, 3, 2]
>>> idx = np.empty_like(permutation)
>>> idx[permutation] = np.arange(len(permutation))
>>> a[:, idx]  # return a rearranged copy
array([[10, 30, 50, 40, 20],
       [ 6,  8, 10,  9,  7]])
>>> a[:] = a[:, idx]  # in-place modification of a

Note that a[:, idx] is returning a copy, not a view. An O(1)-space solution is not possible in the general case, due to how numpy arrays are strided in memory.

这篇关于重新排列 numpy 二维数组的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆