Python numpy: create 2d array of values based on coordinates

前端 未结 5 823
太阳男子
太阳男子 2020-12-24 15:34

I have a file containing 3 columns, where the first two are coordinates (x,y) and the third is a value (z) corresponding to that position. Here\'s a short example:



        
5条回答
  •  粉色の甜心
    2020-12-24 15:57

    If you have scipy installed, you could take advantage of its sparse matrix module. Get the values from the text file with genfromtxt, and plug those 'columns' directly into a sparse matrix creator.

    In [545]: txt=b"""x y z
    0 1 14
    0 2 17
    1 0 15
    1 1 16
    2 1 18
    2 2 13
    """
    
    In [546]: xyz=np.genfromtxt(txt.splitlines(),names=True,dtype=int)
    
    In [547]: sparse.coo_matrix((xyz['z'],(xyz['y'],xyz['x']))).A     
    Out[547]: 
    array([[ 0, 15,  0],
           [14, 16, 18],
           [17,  0, 13]])
    

    But Joe's z_array=np.zeros((3,3),int); z_array[xyz['y'],xyz['x']]=xyz['z'] is considerably faster.

提交回复
热议问题