使用scipy.interpolate.griddata用于从xarray对多维数据进行插值

2024-10-05 10:48:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为xarrayDataSet的降雨数据,名为longitudelatitude和{}:

<xarray.Dataset>
Dimensions:    (latitude: 691, longitude: 886, time: 1)
Coordinates:
  * longitude  (longitude) float64 112.0 112.0 112.1 112.1 ... 156.2 156.2 156.3
  * latitude   (latitude) float64 -9.975 -10.03 -10.08 ... -44.42 -44.47 -44.52
  * time       (time) datetime64[ns] 1980-01-03
Data variables:
    RAIN       (time, latitude, longitude) float64 0.0 0.0 0.0 ... 0.0 0.0 0.0

我想根据另一组经纬度来插值降雨值:EXAMPLE_FFDI_LON_XR_DA和{}。它们的值与ds的经纬度完全不同。

示例\u FFDI_LON_XR_DA:

^{pr2}$

示例:LAT_XR_DA:

<xarray.DataArray 'latitude' (latitude: 106)>
array([-39.2     , -39.149525, ... ...], dtype=float32)
Coordinates:
  * latitude  (latitude) float32 -39.2 -39.149525 -39.09905 ... -33.950478 -33.9
Attributes:
    latIntersect:         0.0
    lonCentre:            145.4
    units:                degrees_north
    projectionType:       MERCATOR
    _CoordinateAxisType:  Lat

我考虑过使用xarray xarray.DataArray.interp函数,但这只支持nearest方法。我是scipy的新手,但我认为使用scipy库scipy.interpolate.griddata函数进行插值会更好地满足我的需要。我怎样才能对我的数据使用这个函数?一个有效的例子会很有帮助。


Tags: 数据函数timescipyda插值经纬度xarray
1条回答
网友
1楼 · 发布于 2024-10-05 10:48:25

我不确定是否有可能让scipy与DataArray对象进行交互,就像您现在所拥有的那样。你可以做的是:

from scipy.interpolate import griddata
import xarray
import numpy as np
# construct a dummy df like you have
values = np.random.rand(10, 30, 30) * 100
df = xarray.DataArray(values, [('time', range(10)), ('latitude', range(30)), ('longitude', range(30))])
# extract the values from the array
latitude = df['latitude'].values
longitude = df['longitude'].values
length_values = len(latitude) * len(longitude)

# create grid
x_grid, y_grid = np.meshgrid(latitude, longitude)
points = np.empty((length_values, 2))
points[:, 0] = x_grid.flatten()
points[:, 1] = y_grid.flatten()

# select a single timestep in which to interpolate the data
rain_at_locations = df.where(df.time == 3, drop=True)
values = np.array(rain_at_locations.values.flatten())

#your test locations
EXAMPLE_FFDI_LAT_XR_DA = range(5, 15) # extract these from you arrays
EXAMPLE_FFDI_LON_XR_DA = range(20, 30)
grid_x, grid_y = np.meshgrid(EXAMPLE_FFDI_LAT_XR_DA, EXAMPLE_FFDI_LON_XR_DA)

interpolated_values = griddata(points, values, (grid_x, grid_y), method='cubic')

然后可以将这些值重新提供给数据数组。在

相关问题 更多 >

    热门问题