我有一个“dataarray”,我正在尝试使用 roxarray 重新投影它。但是,当我使用 xarray.to_netcdf 进行重投影后,保存的文件是一个数据集,其中“spatial_ref”坐标转换为变量。我不确定是 xarray 还是 rioxarray.reprojection 导致了这种行为。以下是一些显示问题的代码:
import xarray as xr
import rioxarray
from pyproj import CRS
lst = xr.open_dataset("lst.nc") # File which carries the original CRS
luc = xr.open_rasterio("luc.tif") # File with the desired projection system
file_to_reproject = xr.open_dataarray("myfile.nc") # File to reproject
cc_lst = CRS.from_cf(lst.crs.attrs) # Get the CRS
cc_luc = luc.rio.crs
file_to_reproject = file_to_reproject.rio.write_crs(cc_lst) # write crs
file_reprojected= file_to_reproject.rio.reproject(cc_luc) #reproject the file
print(file_reprojected)
<xarray.DataArray (season: 4, y: 4343, x: 4172)>
array([[[nan, nan, nan, ..., nan, …Run Code Online (Sandbox Code Playgroud) 我有一个 xarray 数据集,其中包含时间、纬度、经度和压力水平维度。纬度从 90\xc2\xb0 到 -90\xc2\xb0。但我需要从 -90\xc2\xb0 到 90\xc2\xb0 的它们。如何以改变变量维度的方式扭转维度?
\n\n我有三个变量(T2M、U50M、V50M),我想从中找到多年来的一月平均值、二月平均值等。我有一个 xarry.Dataset - 名称 Multidata:
Dimensions: (time: 17520, lat: 17, lon: 15)
Coordinates:
* lat (lat) float64 47.0 47.5 48.0 48.5 49.0 ... 53.0 53.5 54.0 54.5 55.0
* lon (lon) float64 6.25 6.875 7.5 8.125 8.75 ... 13.12 13.75 14.38 15.0
* time (time) datetime64[ns] 2001-01-01T00:30:00 ... 2002-12-31T23:30:00
Data variables:
T2M (time, lat, lon) float32 dask.array<chunksize=(24, 17, 15), meta=np.ndarray>
V50M (time, lat, lon) float32 dask.array<chunksize=(24, 17, 15), meta=np.ndarray>
U50M (time, lat, lon) float32 dask.array<chunksize=(24, 17, 15), meta=np.ndarray>
Run Code Online (Sandbox Code Playgroud)
我尝试过: ---- …
我想使用 xarray 创建一个数据集,并希望在创建数据集时向变量添加属性。xarray文档提供了一种添加全局属性的方法。例如如下:
ds = xr.Dataset(
data_vars=dict(
'temperature'=(["x", "y", "time"], temperature),
'precipitation'=(["x", "y", "time"], precipitation),
),
coords=dict(
lon=(["x", "y"], lon),
lat=(["x", "y"], lat),
time=time,
reference_time=reference_time,
),
attrs=dict(description="Weather related data."),)
Run Code Online (Sandbox Code Playgroud)
添加变量属性的一种方法是这样的:
ds['temperature'].attrs = {"units": K, '_FillValue': -999}
Run Code Online (Sandbox Code Playgroud)
但是,在我看来,这更像是更新属性。有没有办法在直接使用创建数据集时直接分配属性xr.Dataset?
当使用 xarray 在 x,y 位置选择数据时,我会获取任何 x,y 对的数据。我希望从选择中获得一维数组而不是二维数组。有没有有效的方法来做到这一点?(现在我正在用 for 循环来做......)
x = [x1,x2,x3,x4] y = [y1,y2,y3,y4]
DS = 二维数组
subset = Dataset.sel(longitude=x, latitude=y, method='nearest')
Run Code Online (Sandbox Code Playgroud)
换句话说,我希望数据集位于 [x1,y1]、[x2,y2]、[x3,y3]、[x4,y4],而不是其他位置,即 [x1,y2]。
我正在尝试使用 xarray 打开 RINEX 数据集。虽然我已经安装了“netcfd4”和“scipy”,但我收到以下值错误。
ValueError: did not find a match in any of xarray's currently installed IO backends ['netcdf4', 'scipy']. Consider explicitly selecting one of the installed engines via the ``engine`` parameter, or installing additional IO dependencies, see:
http://xarray.pydata.org/en/stable/getting-started-guide/installing.html
http://xarray.pydata.org/en/stable/user-guide/io.html
Run Code Online (Sandbox Code Playgroud)
当我再次尝试安装 scipy 和 netcdf4 时,我收到以下消息。
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: netcdf4 in c:\users\sdasgupta.student\appdata\roaming\python\python39\site-packages (1.6.1)
Requirement already satisfied: numpy>=1.9 in c:\programdata\anaconda3\lib\site-packages (from netcdf4) (1.21.5)
Requirement already satisfied: cftime in c:\users\sdasgupta.student\appdata\roaming\python\python39\site-packages (from netcdf4) …Run Code Online (Sandbox Code Playgroud) 当我在 numpy 中使用权重进行跑步/滚动平均时,我会做这样的事情:
data = np.random.random(100) # Example data...
weights = np.array([1, 2, 1])
data_m = np.convolve(data, weights/float(np.sum(weights)), "same")
Run Code Online (Sandbox Code Playgroud)
然后根据应用将 data_m[0] 和 data_m[-1] 替换为 nans 等。
可以用 xarray 做类似的事情。我所做的(在这种情况下)是
xr.DataArray(data).rolling(dim_0=3, center=True).mean(dim="dim_0")
Run Code Online (Sandbox Code Playgroud)
但这对应于权重
weights = np.array([1, 1, 1])
Run Code Online (Sandbox Code Playgroud)
在 numpy 示例中。使用 xarray 时,我将如何应用其他权重?
我在 xarray 数据集中加载了 Netcdf 文件,我想制作没有闰日的日常气候学,即不包含 2 月 29 日。我正在尝试该Dataset.drop方法的语法对我来说不是那么直观。这是数据集
print(ds)
>><xarray.Dataset>
Dimensions: (lat: 1, lev: 1, lon: 720, time: 27133)
Coordinates:
* lon (lon) float32 -180.0 -179.5 -179.0 ... 178.5 179.0 179.5
* lev (lev) float32 1.0
* time (time) datetime64[ns] 2000-01-02T18:00:00 ... 2018-07-30
Dimensions without coordinates: lat
Data variables:
Var1 (time, lev, lon) float32 ...
Var2 (time, lat, lon) float64 ...
Var3 (time, lat, lon) float64 ...
Run Code Online (Sandbox Code Playgroud)
我试过
ds_N_R.drop(['Var1', 'Var2', 'Var3'], time='2000-02-29')
>>TypeError: drop() got …Run Code Online (Sandbox Code Playgroud) 问题:
当至少一个输入值是 nan 时,我想重新采样一个 xarray 数据集,例如总和或平均值,每个结果值都是 nan。使用 pandas,我可以轻松应用自己的均值、求和等函数,为我提供我喜欢的 nan 处理。xarray 也允许 resample.apply(own_func) 但我在定义自己的 func 时遇到问题。
示例(来自 xarray 的文档):
dat=np.linspace(0, 11, 12)
dat[2]=np.nan
da = xr.DataArray(dat,
coords=[pd.date_range('15/12/1999',
periods=12,
freq=pd.DateOffset(months=1))],
dims='time')
da.resample(time="QS-DEC").sum()
Run Code Online (Sandbox Code Playgroud)
我得到的:
<xarray.DataArray (time: 4)>
array([ 1., 12., 21., 30.])
Coordinates:
* time (time) datetime64[ns] 1999-12-01 2000-03-01 2000-06-01 2000-09-01
Run Code Online (Sandbox Code Playgroud)
@JulianGiles 回答:
da.resample(time="QS-DEC",skipna=False).mean()
<xarray.DataArray (time: 4)>
array([ 0.5, 4. , 7. , 10. ])
Coordinates:
* time (time) datetime64[ns] 1999-12-01 2000-03-01 2000-06-01 2000-09-01
Run Code Online (Sandbox Code Playgroud)
我想要的是:
<xarray.DataArray (time: 4)>
array([ …Run Code Online (Sandbox Code Playgroud) 我在 s3 中有每月的 zarr 文件,这些文件具有网格化的温度数据。我想为一个纬度/经度提取多个月的数据并创建该时间序列的数据框。一些伪代码:
datasets=[]
for file in files:
s3 = s3fs.S3FileSystem()
zarr_store = s3fs.S3Map(file, s3=s3)
zarr = xr.open_zarr(store=zarr_store, consolidated=True)
ds = zarr.sel(latitude=lat,
longitude=long,
time=slice(start_date.strftime("%Y-%m-%d"),
end_date.strftime("%Y-%m-%d"))
)
datasets.append(ds)
con = xr.concat(datasets, dim='time')
df = con.to_dataframe()
Run Code Online (Sandbox Code Playgroud)
所以这段代码可以工作,但速度非常慢。我希望使用 dask 来加快速度。我的计划是更改一次处理一个文件并返回一个数据帧的方法。然后我会调用 client.map() 并生成所有 dfs,然后在最后将它们连接在一起。所以我结束了类似的事情:
def load(file, lat: float, long: float, start_date, end_date):
s3 = s3fs.S3FileSystem()
s3_path = file['s3_bucket'] + '/' + file['zarr_s3_key']
zarr_store = s3fs.S3Map(s3_path, s3=s3)
zarr = xr.open_zarr(store=zarr_store, consolidated=True)
ds = zarr.sel(latitude=lat,
longitude=long,
time=slice(start_date.strftime("%Y-%m-%d"),
end_date.strftime("%Y-%m-%d"))
)
tmp = x.result().to_array().values
df_time = …Run Code Online (Sandbox Code Playgroud)