How to generate a 2d grid (X,Y) with a Z value using numpy or pandas?

Question:

As the title states I want to generate a 2d grid. Essentially X, Y coordinates with a Z value. I want this grid to go from X: -175:175 Y: -175:175 and fill in all Z values with 0. I also already have some X,Y, and Z values in a df that I’ve created like:

+-----+-----+--------+
|  X  |  Y  |   Z    |
+-----+-----+--------+
| -45 |   3 |   -.03 |
|  10 |   4 |    .06 |
|  20 | -97 | -.0345 |
+-----+-----+--------+

Then I create a very basic grid with:

grid = np.zeros((350, 350))

Now I want to create a df (or np array) that will go from -175 to 175 (both X in Y) and fill those values with my df and if they don’t exist in my df just fill them with 0.

The ultimate goal is to graph those x,y,z points (Maybe in a heat map or something not sure yet) if that helps give some context.

All help is appreciated and thanks in advance!

Asked By: mike_gundy123

||

Answers:

You can try pivot:

(df.pivot(index='X', columns='Y', values='Z')9
   .reindex(np.arange(-175,175))
   .reindex(np.arange(-175,175), axis=1)
   .fillna(0)
)
Answered By: Quang Hoang

if you just want to plot x,y,z (as value) use: contourf from matplotlib (https://matplotlib.org/stable/gallery/images_contours_and_fields/contourf_demo.html#contourf-demo)

Answered By: Berta Pi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.