Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从一维数组中获取二维索引数组?_Python_Numpy - Fatal编程技术网

Python 如何从一维数组中获取二维索引数组?

Python 如何从一维数组中获取二维索引数组?,python,numpy,Python,Numpy,我正在寻找一种基于一维数组中的值返回二维数组索引的有效方法。我目前有一个嵌套的for循环设置,速度非常慢 以下是一些示例数据和我想要得到的: data2d = np.array( [ [1,2] , [1,3] ,[3,4], [1,2] , [7,9] ]) data1d = np.array([1,2,3,4,5,6,7,8,9]) 我想返回data2d等于data1d的索引。我想要的输出是这个2d数组: locs = np.array([[0, 1], [0, 2], [2, 3],

我正在寻找一种基于一维数组中的值返回二维数组索引的有效方法。我目前有一个嵌套的for循环设置,速度非常慢

以下是一些示例数据和我想要得到的:

data2d = np.array( [  [1,2] , [1,3] ,[3,4], [1,2] , [7,9] ])

data1d = np.array([1,2,3,4,5,6,7,8,9])
我想返回data2d等于data1d的索引。我想要的输出是这个2d数组:

locs = np.array([[0, 1], [0, 2], [2, 3], [0, 1], [6, 8]])
我唯一想到的是嵌套for循环:

locs = np.full((np.shape(data2d)), np.nan)

for i in range(0, 5):
    for j in range(0, 2):
        loc_val = np.where(data1d == data2d[i, j])
        loc_val = loc_val[0]
        locs[i, j] = loc_val

这对于一小部分数据来说是很好的,但我有87600个二维网格,每个网格点为428x614个网格点。

这应该也很快

import numpy as np
data2d = np.array( [  [1,2] , [1,3] ,[3,4], [1,2] , [7,9] ])
data1d = np.array([1,2,3,4,5,6,7,8,9])
idxdict = dict(zip(data1d,range(len(data1d))))
locs = data2d
for i in range(len(locs)):
    for j in range(len(locs[i])):
        locs[i][j] = idxdict[locs[i][j]]
使用:

searchsorted
使用ravelled
data2d
执行二进制搜索。然后对结果进行重塑


另一种选择是构建索引并在固定时间内查询它。您可以使用pandas的
Index
API来实现这一点

import pandas as pd

idx = pd.Index([1,2,3,4,5,6,7,8,9])
idx
#  Int64Index([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')

idx.get_indexer(data2d.ravel()).reshape(data2d.shape)

array([[0, 1],
       [0, 2],
       [2, 3],
       [0, 1],
       [6, 8]])

data1d
是否已排序?此外,是否保证data2中的所有点都存在于data1中?是的,它已针对我正在处理的数据进行排序。是的,所有的点都保证存在。哇,这两个看起来都是很好的解决方案,谢谢!现在我只需要看看它在更大数据上的表现。
import pandas as pd

idx = pd.Index([1,2,3,4,5,6,7,8,9])
idx
#  Int64Index([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')

idx.get_indexer(data2d.ravel()).reshape(data2d.shape)

array([[0, 1],
       [0, 2],
       [2, 3],
       [0, 1],
       [6, 8]])