将多维数组转换为2d并随后进行索引

时间:2019-05-24 18:14:25

标签: python numpy multidimensional-array indexing sparse-matrix

我有一些代码在逻辑上最好设置为高度嵌套的数组。 整体结构具有高维度和稀疏性,因此我不得不根据稀疏实现的要求将其转换为2d矩阵,这样它才能适合内存。

我现在发现自己在两种格式之间切换,这既复杂又令人困惑。我写了一个小函数,它从嵌套输入中将计算2d单元格,但是如果我要进行范围查询,它将变得更加复杂。

import numpy as np

dim1 = 1
dim2 = 2
dim3 = 3
dim4 = 4 
dim5 = 5
dim6 = 6

sixD = np.arange(720).reshape(dim1, dim2, dim3, dim4, dim5, dim6)

twoD = sixD.transpose(0,1,2,3,4,5).reshape(dim1,-1)

def sixDto2DCell(a, b, c, d, e, f):
  return [a, (b*dim3*dim4*dim5*dim6) + 
    (c*dim4*dim5*dim6) + 
    (d*dim5*dim6) + 
    (e*dim6) + 
    f]

x, y = sixDto2DCell(0, 1, 2, 3, 4, 5)
assert(sixD[0, 1, 2, 3, 4, 5] == twoD[x, y])

所以我正在尝试对类似的查询做些什么

sixD[0, 1, 0:, 3, 4, 5]

在二维矩阵中返回相同的值

我需要编写一个新函数,还是想念实现相同功能的内置numpy方法?

任何帮助将不胜感激:-)

1 个答案:

答案 0 :(得分:1)

方法1

这是一种从2D稀疏矩阵或任何2D数组中提取数据的方法,该方法具有相应的n-dim数组及其沿每个轴的起始索引和结束索引-

def sparse_ndim_map_indices(ndim_shape, start_index, end_index):       
    """
    Get flattened indices for indexing into a sparse array mapped to
    a corresponding n-dim array.
    """        

    # Get shape and cumulative shape info for use to get flattened indices later
    shp = ndim_shape
    cshp = np.r_[np.cumprod(shp[::-1])[::-1][1:],1]

    # Create open-ranges
    o_r = np.ix_(*[s*np.arange(i,j) for (s,i,j) in zip(cshp,start_index,end_index)])

    id_ar = np.zeros(np.array(end_index) - np.array(start_index), dtype=int)
    for r in o_r:
        id_ar += r
    return id_ar

使用提供的样本来研究样本案例运行-

In [637]: start_index = (0,1,1,1,4,3)
     ...: end_index =   (1,2,3,4,5,6)
     ...: 
     ...: out1 = sixD[0:1, 1:2, 1:3, 1:4, 4:5, 3:6]

In [638]: out1
Out[638]: 
array([[[[[[537, 538, 539]],

          [[567, 568, 569]],

          [[597, 598, 599]]],


         [[[657, 658, 659]],

          [[687, 688, 689]],

          [[717, 718, 719]]]]]])

In [641]: idx = sparse_ndim_map_indices(sixD.shape, start_index, end_index)

In [642]: twoD[:,idx.ravel()]
Out[642]: 
array([[537, 538, 539, 567, 568, 569, 597, 598, 599, 657, 658, 659, 687,
        688, 689, 717, 718, 719]])

方法2

这里是沿每个轴创建索引的所有组合,然后使用np.ravel_multi_index获得展平的索引的另一种方法-

import itertools

def sparse_ndim_map_indices_v2(ndim_shape, start_index, end_index):    
    # Create ranges and hence get the flattened indices
    r = [np.arange(i,j) for (i,j) in zip(start_index,end_index)]
    return np.ravel_multi_index(np.array(list(itertools.product(*r))).T, ndim_shape)