3

I've got a pandas DataFrame containing lat, lon, val.

lat  lon  val
50   60   1
51   60   2
52   60   3
50   61   7
51   61   8
52   61   9

To use matlibplot.contourf, I have to send grid data, instead of vectors.

To this, I use numpy.meshgrid, to generate

lat = [50, 51, 52, 50, 51, 52]
lon = [60, 60, 60, 61, 61, 61]
x, y = np.meshgrid(lat, lon)

lat = 50 51 52 50 51 52
      50 51 52 50 51 52
      50 51 52 50 51 52
      50 51 52 50 51 52
      50 51 52 50 51 52
      50 51 52 50 51 52

lon = 60 60 60 60 60 60
      60 60 60 60 60 60
      60 60 60 60 60 60
      61 61 61 61 61 61
      61 61 61 61 61 61
      61 61 61 61 61 61

Now, I need to create the val as:

val = 1 2 3 1 2 3 
      1 2 3 1 2 3
      1 2 3 1 2 3
      7 8 9 7 8 9
      7 8 9 7 8 9
      7 8 9 7 8 9

But I have no ideia how to do that "the proper way".

Of course, I can create an empty 3x3 array len(lat x lon), iterate over their keys, and populate the values. But it seems to be the wrong way to do it.

Also, there is the DataFrame.applymap, so I don't get my "hands dirty" making the iteration, but it also feels wrong (and slow).

How can I create the val array?

Gustavo Lopes
  • 3,794
  • 4
  • 17
  • 57

1 Answers1

1

You will need a 2 by 3 grid:

lat = [50, 51, 52, 50, 51, 52]
lon = [60, 60, 60, 61, 61, 61]
val = [1,2,3,7,8,9]

x = np.array(lat).reshape(2,3)
y = np.array(lon).reshape(2,3)
z = np.array(val).reshape(2,3)

plt.contourf(x,y,z)

More information in the dupe: Make contour of scatter

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712