Hugo
Hugo

Reputation: 1688

How do I reshape a numpy array for use with scipy interpolate?

I have 3 numpy arrays with long, lat and rain values:

[-7.4989786799999996, -7.5215012000000003, -7.4764561599999997, -7.4989786799999996, -7.5215012000000003, -7.4764561599999997]

[41.90415308, 41.90415308, 41.90415308, 41.881630559999998, 41.881630559999998, 41.881630559999998]

[0.020928397800000002, 0.0299166963, 0.0171956848, 0.0340920761, 0.0429551788, 0.0301877651]

Scipy interpolate requires 1 array with 3 distinct Lons, another one with 2 distinct lons and a 3x2 array of rain values. How can I reshape them?

Upvotes: 1

Views: 1302

Answers (1)

Joe Kington
Joe Kington

Reputation: 284582

It sounds like you're wanting a 2D interpolation.

For example, let's use some random data similar to yours and plot it:

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1) # Make example exactly reproducable

num_points = 20
lon = 0.1 * np.random.random(num_points) - 7.5
lat = 0.1 * np.random.random(num_points) + 41.8
z = 0.05 * np.random.random(num_points)

fig, ax = plt.subplots()
artist = ax.scatter(lon, lat, c=z, s=200, cmap='gist_earth')
fig.colorbar(artist)
ax.axis('tight')
plt.show()

enter image description here

For this case, a good choice of interpolation algorithm would be a Radial Basis Function of some sort (e.g. a spline). In scipy, that's scipy.interpolate.Rbf:

import scipy.interpolate

interp = scipy.interpolate.Rbf(lon, lat, z, function='linear')

# 20x20 grid of points to interpolate on
yy, xx = np.mgrid[lat.min():lat.max():20j, lon.min():lon.max():20j]

zi = interp(xx, yy)

# Plot the results
fig, ax = plt.subplots()
artist = ax.scatter(lon, lat, c=z, s=100, cmap='gist_earth',
                     vmin=zi.min(), vmax=zi.max())
ax.pcolormesh(xx, yy, zi, cmap='gist_earth')
ax.axis('tight')
plt.show()

enter image description here

Upvotes: 5

Related Questions