python - 在numpy中,如何创建源数组中元素的索引数组,因为它们在目标数组中找到?
问题描述
我确信这个问题已经在某个地方得到了回答,但我就是找不到要寻找的词。
我有这两个数组:
import numpy as np
src = np.array([[8, 1],
[2, 4]])
dst = np.array([[1, 4],
[8, 2]])
我想得到这个数组:
indices = (np.array([[1, 0],
[1, 0]]),
np.array([[0, 0],
[1, 1]]))
这样dst[indices]
我就明白了src
。
有任何想法吗?此外,我正在寻找什么样的操作?这样我以后可以自己搜索更多。
解决方案
这是我认为是“直接”的方式:
# find order of src and dst
so = src.ravel().argsort()
do = dst.ravel().argsort()
# allocate combined map
tot = np.empty_like(src)
# next line is all you need to remember
tot.ravel()[so] = do
# go back to 2D indexing
indices = np.unravel_index(tot,dst.shape)
# check
dst[indices]
# array([[8, 1],
# [2, 4]])
indices
# (array([[1, 0],
# [1, 0]]), array([[0, 0],
# [1, 1]]))
推荐阅读
- r - 无法使用 %in% 将列表传递给 dplyr 过滤器
- java - 具有序列化对象列的 Ebean 数据库模型
- json - 如何递归地将JSON字符串中的所有数组转换为Delphi中的数据集?
- r - Case_when 错误'x 必须是字符向量,而不是双向量'?
- python - 如何将 2 元素列表作为键/值对添加到 python 字典中?
- python-3.x - 在 Windows 10 中安装 fastparquet 时出错
- python - predict_proba() 中的前 3 个类
- python - xarray weighted().mean() 使用哪种精度?
- python - 在使用 Django 的模型上使用原始查询时,如何返回附加数据?
- jquery - 对于某些用户,POST 和 GET 同时从 Ajax POST JS 提交(双重请求)