python - 相对于另一个数组对数组进行排序
问题描述
我在我的程序中使用了一些数据,如果我有一些排序问题,这对我来说需要更长的时间。所以我在这里提到了一个例子,我想得到一个解决方案。
import numpy as np
A = np.array([[1,2,3],[4,5,6],[7,8,9]])
B = np.array([[4,5,6,7],[7,8,9,4],[1,2,3,2]])
# Need to apply some sort function
C = sort(B[:,0:3] to be sorted with respect to A)
print(C)
我有两个 numpy 数组,我希望数组 B 的前 3 列相对于数组 A 进行排序。
我希望 C 的输出为
[[1,2,3,2],[4,5,6,7],[7,8,9,4]]
是否有任何 numpy 方法或任何其他 python 库可以做到这一点。
期待一些答案
问候
阿迪提亚
解决方案
这仅在使用第一列时有效:
_, indexer, _ = np.intersect1d(B[:,:1], A[:,:1], return_indices=True)
B[indexer]
array([[1, 2, 3, 2],
[4, 5, 6, 7],
[7, 8, 9, 4]])
显然,上述解决方案仅在值唯一的情况下才有效(感谢@AadithyaSaathya。
如果我们要使用所有 A,我们可以使用 itertools 的产品功能:
from itertools import product
indexer = [B[0]
for A,B
in
product(enumerate(A), enumerate(B[:,:3]))
if np.all(np.equal(A[-1], B[-1]))]
B[indexer]
array([[1, 2, 3, 2],
[4, 5, 6, 7],
[7, 8, 9, 4]])
推荐阅读
- flutter - 在 Flutter Web 版本中禁用控制台
- visual-studio-code - 我的终端在 vs-code 中表现得很奇怪,每个字符之间都有空格吗?
- firebase - 有没有办法为 Firebase 云功能设置计费限制?(通过 GCP 或 firebase 本身)
- python - 类型错误:参数 1 必须是字符串或 unicode 对象:改为获取元组
- robotframework-ide - 无法运行程序“robot”(在目录“/Users/Seema/Robot/freecrm_repo”中):错误=2,没有这样的文件或目录
- stanza - 如果存在元组中的元素,如何找到它的索引?
- python - 在 Python 中解析凌乱的 XML
- c++ - 禁用定时器时出现硬故障?
- unit-testing - 如何对 registry.gitlab.com 中的镜像进行单元测试和部署到自托管 microk8s
- java - Firebase 管理员 - Gradle - Fat Jar - 无法正常工作