pydata / xarray

N-D labeled arrays and datasets in Python
https://xarray.dev
Apache License 2.0
3.63k stars 1.09k forks source link

moving data array from 2d coordinate to 1d coordinate #9734

Open 3dfirelab opened 2 weeks ago

3dfirelab commented 2 weeks ago

What is your issue?

I have a data array with 2d coordinate array

<xarray.DataArray (y: 200, x: 100)> Size: 160kB
...
Coordinates:
    latitude     (y, x) float64 160kB -90.0 -88.18 -86.36 ... 86.36 88.18 90.0
    longitude    (y, x) float64 160kB -180.0 -180.0 -180.0 ... 180.0 180.0 180.0
    spatial_ref  int64 8B 0
Dimensions without coordinates: y, x

I try to interpolate it on 1D coordinate however da.interp is expecting input of dimension name. So the code below does not work. Is there any work around?

import xarray as xr
import rioxarray
import numpy as np
import matplotlib.pyplot as plt

# Define 1D latitude and longitude
lat = np.linspace(-90, 90, 100)   # 1D array for latitude
lon = np.linspace(-180, 180, 200)  # 1D array for longitude

# Create a 2D data array, but using 1D coordinates for lat and lon
data = np.random.rand(100, 200)  # Data array of size (lat, lon)

# Set up the DataArray with 1D coordinates
da = xr.DataArray(
    data.T,
    coords={"latitude":  (["y", "x"],np.meshgrid(lat, lon)[0]),
            "longitude": (["y", "x"],np.meshgrid(lat, lon)[1]),
            },
    dims=["y", "x"]
)

da = da.rio.write_crs("EPSG:4326", inplace=True)

new_lat = np.linspace(-90, 90, 100)   # 1D array for latitude
new_lon = np.linspace(-180, 180, 200)  # 1D array for longitude

interpolated_data = da.interp(latitude=new_lat, longitude=new_lon)

error is

da can however be plotted on latitude and longitude using

da.plot(x='longitude',y='latitude')
plt.show()
welcome[bot] commented 2 weeks ago

Thanks for opening your first issue here at xarray! Be sure to follow the issue template! If you have an idea for a solution, we would really welcome a Pull Request with proposed changes. See the Contributing Guide for more. It may take us a while to respond here, but we really value your contribution. Contributors like you help make xarray better. Thank you!

delgadom commented 2 weeks ago

Hi @3dfirelab - this seems like it would be a great question for StackOverflow or the xarray github Discussions forum, since it's not a bug with xarray, but more a usage question. Working with 2D coordinates is tricky! If you do ask on Discussions, be sure to check out the Discussions norms guide. Good luck!

Here's a relevant StackOverflow question: https://stackoverflow.com/questions/58758480/xarray-select-nearest-lat-lon-with-multi-dimension-coordinates?rq=1