python - 如何在 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]])
解决方案
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]]
推荐阅读
- firebase - Flutter DataTable 表头重复
- azure - 如何从 Create-React-App 动态检索 Application Insights Instrumentation Key
- postgresql - 具有 SSL 身份验证的 Amazon RDS for PostgreSQL 数据库?
- javascript - 我单击的点到最近的点之间的折线
- android - 如何从 Android 中的 Google FIT 获取历史距离日期?
- python - 绑定参数动态更新表名
- kubernetes - Kubernetes 节点亲和性偏好具有最高值的节点
- ruby-on-rails - ActiveRecord:查询父记录,其中子记录在 AND 查询中具有某些值
- c++ - C++ libcurl:使用非阻塞循环检测 HTTP 状态码变化
- python - 在 Pandas 中创建列的副本