1

Here is some code I'm struggling with.

My goal is to create an array (db) from an existing one (t) , in db each line will represent a value of t. db will have 3 column, 1 for line index in t, 1 for column index in t and 1 for the value in t.

In my case, t was a distance matrix, thus diagonal was 0 and it was symetric, I replaced lower triangular values with 0. I don't need 0 values in the new array but I can just delete them in another step.

import numpy as np

t = np.array([[0, 2.5],
              [0, 0]])

My goal is to obtain a new array such as :

db = np.array([[0, 0, 0], 
              [0, 1, 2.5],  
              [1, 0, 0], 
              [1, 1, 0]])

Thanks for your time.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
yacx
  • 167
  • 2
  • 13

1 Answers1

0

You can create a meshgrid of 2D coordinates for the rows and columns, then unroll these into 1D arrays. You can then concatenate these two arrays as well as the unrolled version of t into one final matrix:

import numpy as np
(Y, X) = np.meshgrid(np.arange(t.shape[1]), np.arange(t.shape[0]))
db = np.column_stack((X.ravel(), Y.ravel(), t.ravel()))

Example run

In [9]: import numpy as np

In [10]: t = np.array([[0, 2.5],
    ...:               [0, 0]])

In [11]: (Y, X) = np.meshgrid(np.arange(t.shape[1]), np.arange(t.shape[0]))

In [12]: db = np.column_stack((X.ravel(), Y.ravel(), t.ravel()))

In [13]: db
Out[13]:
array([[ 0. ,  0. ,  0. ],
       [ 0. ,  1. ,  2.5],
       [ 1. ,  0. ,  0. ],
       [ 1. ,  1. ,  0. ]])
rayryeng
  • 102,964
  • 22
  • 184
  • 193