首页 > 解决方案 > 如何在 Python 中移动 numpy 数组中的项目?

问题描述

我还没有找到一个简单的解决方案来移动 NumPy 数组中的元素。

给定一个数组,例如:

>>> A = np.arange(10).reshape(2,5)
>>> A
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])

并给定要移动的元素(在本例中为列)的索引,例如[2,4],我想将它们移动到某个位置和连续的位置,例如p = 1,将其他元素向右移动。结果应如下所示:

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

标签: pythonnumpy

解决方案


m您可以为排序顺序创建掩码。首先我们将列 < 设置p-1,然后将要插入的列设置为0,其余列保持在1。默认排序类型 'quicksort'是不稳定的,所以为了安全起见,我们kind='stable'在使用时指定argsort对掩码进行排序并从该掩码创建一个新数组:

import numpy as np

A = np.arange(10).reshape(2,5)
p = 1
c = [2,4]

m = np.full(A.shape[1], 1)
m[:p] = -1    # leave up to position p as is
m[c] = 0      # insert columns c

print(A[:,m.argsort(kind='stable')])
#[[0 2 4 1 3]
# [5 7 9 6 8]]

推荐阅读