多维数组到二维数组的转换及后续索引

2024-09-30 20:18:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些代码,逻辑上是最好的设置为重嵌套数组。 整体结构是高维稀疏的,所以我必须按照稀疏实现的要求将其转换为二维矩阵,这样它才能适合内存。你知道吗

我现在发现自己在两种格式之间切换,这是复杂和混乱的。我已经编写了一个小函数,从嵌套的输入中计算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方法?你知道吗

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


Tags: 函数代码numpynp矩阵twodreshapedim4
1条回答
网友
1楼 · 发布于 2024-09-30 20:18:43

进近#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)

相关问题 更多 >