sparse 3d matrix/array in Python?

后端 未结 6 1906
借酒劲吻你
借酒劲吻你 2020-12-02 15:13

In scipy, we can construct a sparse matrix using scipy.sparse.lil_matrix() etc. But the matrix is in 2d.

I am wondering if there is an existing data structure for sp

6条回答
  •  离开以前
    2020-12-02 15:39

    I needed a 3d look up table for x,y,z and came up with this solution..
    Why not use one of the dimensions to be a divisor of the third dimension? ie. use x and 'yz' as the matrix dimensions

    eg. if x has 80 potential members, y has 100 potential' and z has 20 potential' you make the sparse matrix to be 80 by 2000 (i.e. xy=100x20)
    x dimension is as usual
    yz dimension: the first 100 elements will represent z=0, y=0 to 99
    ..............the second 100 will represent z=2, y=0 to 99 etc
    so given element located at (x,y,z) would be in sparse matrix at (x, z*100 + y)
    if you need to use negative numbers design a aritrary offset into your matrix translation. the solutio could be expanded to n dimensions if necessary
    from scipy import sparse
    m = sparse.lil_matrix((100,2000), dtype=float)
    
    def add_element((x,y,z), element):
        element=float(element)
        m[x,y+z*100]=element
    
    def get_element(x,y,z):
        return m[x,y+z*100]
    
    add_element([3,2,4],2.2)
    add_element([20,15,7], 1.2)
    print get_element(0,0,0)
    print get_element(3,2,4)
    print get_element(20,15,7)
    print "  This is m sparse:";print m
    
    ====================
    OUTPUT:
    0.0
    2.2
    1.2
      This is m sparse:
      (3, 402L) 2.2
      (20, 715L)    1.2
    ====================
    

提交回复
热议问题