标签: python-xarray

从 (xarray) dask.array 到 numpy 数组的转换非常慢

我最近开始使用 xarray。这是一个非常有用的工具。不过,我遇到了一些小问题,我相信这些问题很容易解决。我的问题是,从多维(时间、纬度、经度)dask.array 我想为给定的纬度和经度值选择时间序列。使用 .sel 进行切片效果非常好且快速,但是当我尝试使用 np.array 选项获取实际值时,需要花费大量时间。\n以下效果非常好:

\n\n
enter code here\n% time y = ENS_MEAN.prec.sel(latitude=20, longitude=20)\n% time ENS_MEAN.prec.sel(latitude=20, longitude=20)\n\nOutput:\n\nCPU times: user 10.7 ms, sys: 908 \xc2\xb5s, total: 11.6 ms\nWall time: 10.6 ms\nCPU times: user 2.94 ms, sys: 0 ns, total: 2.94 ms\nWall time: 2.83 ms\n\n\n\nOut[42]:\n<xarray.DataArray 'prec' (time: 29)>\ndask.array<getitem..., shape=(29,), dtype=float64, chunksize=(29,)>\nCoordinates:\nlongitude  float32 20.0\nlatitude   float32 20.0\n* time       (time) datetime64[ns] 1982-05-01 1983-05-01 1984-05-01 ...\n
Run Code Online (Sandbox Code Playgroud)\n\n

但是当我尝试获取 numpy 数组格式的实际值(见下文)时,转换最多需要 2 分钟。我想知道这个问题是否与块大小有关?

\n\n
%time np.array(y)\n\nCPU times: user 2min 12s, sys: 47.1 s, total: 2min …
Run Code Online (Sandbox Code Playgroud)

python python-xarray

5
推荐指数
1
解决办法
6248
查看次数

xarray 相当于 pandas 减法/加法

我正在寻找一种简洁的方法来对 DataArray 的单个维度进行算术运算,然后将结果作为新的 DataArray 返回(已更改和未更改的部分)。在 pandas 中,我会使用 df.subtract() 来执行此操作,但我还没有找到使用 xarray 执行此操作的方法。

以下是我如何从 pandas 的 x 维度中减去值 2:

data = np.arange(0,6).reshape(2,3)
xc = np.arange(0, data.shape[0])
yc = np.arange(0, data.shape[1])

df1 = pd.DataFrame(data, index=xc, columns=yc)
df2 = df1.subtract(2, axis='columns') 
Run Code Online (Sandbox Code Playgroud)

对于 xarray 虽然我不知道:

da1 = xr.DataArray(data, coords={'x': xc, 'y': yc}, dims=['x' , 'y'])
da2 = ?
Run Code Online (Sandbox Code Playgroud)

python-3.x pandas python-xarray

5
推荐指数
2
解决办法
3631
查看次数

如何将具有complex128数据的xarray.DataArray保存到netcdf

我在 xarray 数据集中有一些复杂的数据(numpy dtype complex128),我想用 to_netcdf 保存它们。我收到以下错误:

TypeError: illegal primitive data type, must be one of dict_keys(['S1', 'i1', 'u1', 'i2', 'u2', 'i4', 'u4', 'i8', 'u8', 'f4', 'f8']), got complex128
Run Code Online (Sandbox Code Playgroud)

我确实知道我正在将数据类型传递给不受支持的底层 netCDF4。我还发现https://unidata.github.io/netcdf4-python/有关 netcdf4 的复合数据类型。但不幸的是,我不知道如何将其应用于我的问题,因为我没有直接使用 netcdf4 库。

我可以将数据类型complex128的数据保存到netcdf,同时保留数据类型(使用xarray.DataArray.to_netcdf)吗?

微量元素:

import numpy as np
import xarray as xr
complex = [np.complex(1.0, 1.0), np.complex(2.0, 1.0), np.complex(3.0, 1.0), np.complex(4.0, 1.0)]
data = xr.DataArray(complex)
data.to_netcdf(r'test.nc')
Run Code Online (Sandbox Code Playgroud)

python python-xarray netcdf4

5
推荐指数
1
解决办法
2867
查看次数

使用 xarray 在 netCDF 中输出 int32 时间维度

假设我的时间数据在 xarray 数据集中如下所示:

ds = xr.Dataset({'time': pd.date_range('2000-01-01', periods=10)})
ds.to_netcdf('asdf.nc')
Run Code Online (Sandbox Code Playgroud)

xarray 的to_netcdf()方法将时间维度输出为 int64:

$ ncdump -v time asdf.nc
netcdf asdf {
dimensions:
    time = 10 ;
variables:
    int64 time(time) ;
        time:units = "days since 2000-01-01 00:00:00" ;
        time:calendar = "proleptic_gregorian" ;
data:

 time = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ;
}
Run Code Online (Sandbox Code Playgroud)

因为我正在使用不支持 int64 的 THREDDS 服务器,所以我希望这些时间数据为 int32。使用 xarray 可以做到这一点吗?

netcdf python-xarray

5
推荐指数
1
解决办法
878
查看次数

Python/Xarray:如何将时间数据类型从 datetime64[ns] 转换为整数(具有适当的单位)?

我使用 Xarray 数据集来包含要输入 TensorFlow DNN 的数据,当我调用该train()函数时,我最终收到此错误:

TypeError: Cannot convert value dtype('<M8[ns]') to a TensorFlow DType.
Run Code Online (Sandbox Code Playgroud)

我的假设是,这是因为数据集的时间维度/坐标变量的 dtypedatetime64[ns]映射到<M8[ns]dtype:

In [1]: np.dtype('datetime64[ns]') == np.dtype('<M8[ns]')
Out[1]: True
Run Code Online (Sandbox Code Playgroud)

我想修改数据集,以便time维度/坐标变量具有整数类型,这可能更适合 TensorFlow。

过去,我总是使用整数类型作为时间变量以及“自 2000-01-01 00:00:00 以来的天数”等单位。在这种情况下,如果使用整数数据类型,则单位需要以分钟或秒为单位,因为时间步长以 30 分钟为增量。

关于我当前时间变量的一些信息:

In [2]: ds['time'].coords['time']
Out[2]: <xarray.DataArray 'time' (time: 720)>
        array(['2000-12-27T00:00:00.000000000', '2000-12-27T00:30:00.000000000',
               '2000-12-27T00:59:59.000000000', ..., '2001-01-10T22:30:00.000000000',
               '2001-01-10T23:00:00.000000000', '2001-01-10T23:29:59.000000000'],
               dtype='datetime64[ns]')
        Coordinates:
          * time     (time) datetime64[ns] 2000-12-27 2000-12-27T00:30:00 ...
        Attributes:
            long_name:  time
        bounds:     time_bnds

In [3]: ds['time'].encoding
Out[3]: {'calendar': 'noleap',
         'dtype': dtype('float64'),
         'original_shape': (720,), …
Run Code Online (Sandbox Code Playgroud)

python pandas python-xarray tensorflow

5
推荐指数
0
解决办法
4270
查看次数

Python xarray 删除所有缺失变量的坐标

我使用 xarray 导入不同的 netCDF 文件,最终需要将它们全部转换为一个 panda 数据帧。这是一个包含天气数据的文件,随着时间的推移,某些纬度和经度的观测值丢失了许多(因为它们位于海洋中部)。坐标:纬度、经度、时间;变量:温度、预温度。在转换为数据框之前,我想摆脱这些缺失的观察/整个坐标。有没有一种简单有效的方法来使用 xarray 来做到这一点?我在文档中没有找到任何内容。

import pandas as pd 
import xarray as xr

path = 'Z:/Research/Climate_change/Climate_extreme_index/CRU data/'
temp_data = path+'cru_ts4.01.1901.2016.tmp.dat.nc'
pre_data = path+'cru_ts4.01.1901.2016.pre.dat.nc'

# Open netcdf 
def open_netcdf(datapath):
    print("Loading data...")
    data = xr.open_dataset(datapath, autoclose=True, drop_variables='stn', cache=True)
    return data
# Merge dataframes
data_temp = open_netcdf(temp_data)
data_pre = open_netcdf(pre_data)
all_data = xr.merge([data_temp, data_pre])

#################################################################
<xarray.Dataset>
Dimensions:  (lat: 360, lon: 720, time: 1392)
Coordinates:
  * lon      (lon) float32 -179.75 -179.25 -178.75 -178.25 -177.75 -177.25 ...
  * lat      (lat) float32 …
Run Code Online (Sandbox Code Playgroud)

python netcdf python-xarray

5
推荐指数
2
解决办法
1万
查看次数

xarray - 使用 groupby 按一年中的每一天的气候每小时 netCDF 数据进行分组

我有一年多地理范围内每小时的 netCDF 气候数据,例如从2017-01-01T00:00:002017-12-31T23:00:00

<xarray.Dataset>
Dimensions:    (latitude: 106, longitude: 193, time: 8760)
Coordinates:
  * latitude   (latitude) float32 -39.2 -39.149525 ... -33.950478 -33.9
  * longitude  (longitude) float32 140.8 140.84792 140.89584 ... 149.95209 150.0
  * time       (time) datetime64[ns] 2017-01-01 ... 2017-12-31T23:00:00
Data variables:
    T_SFC      (time, latitude, longitude) float32 dask.array<shape=(8760, 106, 193), chunksize=(744, 106, 193)>
Attributes:
    creationTime:        1525708833
    creationTimeString:  Mon May  7 09:00:32 PDT 2018
    Conventions:         COARDS
Run Code Online (Sandbox Code Playgroud)

正如它所说,数据具有三个坐标(纬度、经度和时间)和一个变量是每小时温度。

我的代码:

import xarray as xr
mds_temp_path = '../Archive/*/IDV71000_VIC_T_SFC.nc'    # netCDF
mds_temp = …
Run Code Online (Sandbox Code Playgroud)

python netcdf pandas python-xarray

5
推荐指数
1
解决办法
1万
查看次数

将新的 Xarray DataArray 添加到现有的 Zarr 存储而不重写整个数据集?

如何在不覆盖整个内容的情况下DataArray向现有内容添加新内容?Dataset新的DataArray与现有的有一些坐标,但也有新的。在我当前的实现中,Dataset被完全覆盖,而不是仅仅添加新的东西。

现有的DataArray是分块的 zarr 支持DirectoryStore(尽管我对于 S3 存储也有同样的问题)。

import numpy as np
import xarray as xr
import zarr

arr1 = xr.DataArray(np.random.randn(2, 3),
                   [('x', ['a', 'b']), ('y', [10, 20, 30])],
                   name='arr1')

ds = arr1.chunk({'x': 1, 'y': 3}).to_dataset()
Run Code Online (Sandbox Code Playgroud)

ds看起来像这样:

<xarray.Dataset>
Dimensions:  (x: 2, y: 3)
Coordinates:
  * x        (x) <U1 'a' 'b'
  * y        (y) int64 10 20 30
Data variables:
    arr1     (x, y) float64 dask.array<shape=(2, 3), chunksize=(1, 3)>
Run Code Online (Sandbox Code Playgroud)

我将其写入目录存储:

store …
Run Code Online (Sandbox Code Playgroud)

dask python-xarray zarr

5
推荐指数
2
解决办法
4227
查看次数

使用 xarray (pcolormesh) 绘制 2D 数据,同时保持纵横比

我正在尝试使用 xarray (使用matplotlib.pcolormesh)绘制二维数据集,同时保持数据的自然纵横比。

例子:

import xarray as xr
import matplotlib.pyplot as plt

plt.close('all')
data = xr.DataArray(np.random.randn(2, 3), dims=('x', 'y'),coords={'x': [10, 20],'y' : [0,50,100]})
data.plot() # Will produce a square plot
Run Code Online (Sandbox Code Playgroud)

结果是

添加plt.gca().set_aspect('equal')确实以我想要的方式缩放绘图,但是,颜色条的高度没有改变

使用参数sizeaspect、 或figsize也没有帮助。对于上面的例子:

data.plot(size=6, aspect=150 / 30. * 6)
Run Code Online (Sandbox Code Playgroud)

(或具有相同的结果data.plot(figsize=(150 / 30. * 6,6))

哪个更好,但仍然关闭(也许是由于颜色条?)。

python matplotlib python-xarray

5
推荐指数
1
解决办法
2295
查看次数

如何通过 Xarray 计算偏度

我发现 xarray 执行变量重采样以及平均值和标准差计算的惊人能力。

是否有像 .mean() 方法一样在数据时间重采样后直接计算偏度的方法?

谢谢

python resampling skew python-xarray

5
推荐指数
1
解决办法
457
查看次数