Insert values to a 3D numpy array

Asked

Viewed 454 times

0

Hello.

I created the following array numpy as below:

import numpy as np

x = [350, 500, 800, 900, 1000]
y = [1100, 900, 1250, 650, 1200]
z = [50, 150, 300, 200, 500]

arr_2d = np.array(list(zip(x, y)))
arr_2d

array([[ 350, 1100],
       [ 500,  900],
       [ 800, 1250],
       [ 900,  650],
       [1000, 1200]])

After processing this one array with scipy.spatial.Delaunay I got the following:

from scipy.spatial import Delaunay

malha = Delaunay(arr_2d)

triangulos = arr_2d[malha.simplices]
triangulos

array([[[ 800, 1250],
        [ 900,  650],
        [1000, 1200]],

       [[ 800, 1250],
        [ 500,  900],
        [ 900,  650]],

       [[ 500,  900],
        [ 800, 1250],
        [ 350, 1100]]])

Now, I’d like to incorporate the values of z at the array triangulos so that the new array is equal to the following:

array([[[ 800, 1250, 300],
        [ 900,  650, 200],
        [1000, 1200, 500]],

       [[ 800, 1250, 300],
        [ 500,  900, 150],
        [ 900,  650, 200]],

       [[ 500,  900, 150],
        [ 800, 1250, 300],
        [ 350, 1100, 50]]])

I need to implement this to a data that has more than 11,000 lines. Any suggestions how to proceed? Any help will be very welcome. Thank you.

1 answer

1


A simple way seems to be to create a dictionary, where each pair of coordinates x, y taken from the X and Y arrays is the key, and the value of z is the corresponding value.

After the operations to generate the 2D points are completed, this dictionary is used to recover the Z coordinate - let’s see:

(I pasted exactly the examples you have above in the interactive terminal, and continue from there)

In [86]: dict_z = {(px, py): pz for px, py, pz in zip(x, y, z) } 
    ...:                                                                                                                           

In [87]: tri3 = np.array(list(list(list(linha) + [dict_z[tuple(linha)] ] for linha in T) for T in triangulos)) 
    ...:  


In [88]: print(tri3)                                                                                                               
[[[ 800 1250  300]
  [ 900  650  200]
  [1000 1200  500]]

 [[ 800 1250  300]
  [ 500  900  150]
  [ 900  650  200]]

 [[ 500  900  150]
  [ 800 1250  300]
  [ 350 1100   50]]]

Maybe the line "87" where I add the value back has a more elegant way of being written with np.concatenate, or np.hstack - but this way it works there! :-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.