【问题标题】:How to know if a sliced xarray Dataset/DataArray is empty?如何知道切片的 xarray Dataset/DataArray 是否为空?
【发布时间】:2020-01-15 09:43:18
【问题描述】:

我正在使用 Python 语言对 Netcdf 文件应用切片和聚合操作。使用这种文件的一种解决方案是使用 Xarray 库。

我还是库功能的新手,所以我想知道 Xarray 对象是否有一些方法来检查切片的 DataSet/DataArray 是否为空,就像 Pandas 一样(对于 pandas,可以通过 'empty' 方法检查数据帧/系列是否为空)。

我找到的唯一解决方案是始终将 Xarray Dataset/DataArray 转换为 pandas Dataframe/Series,然后检查它是否为空。

这里以代码 sn-p 为例:

import xarray as xr

path = 'my_path_to_my_netcdf_file.nc'

Xarray_DataArray = xr.open_dataset(path)

print(Xarray_DataArray)

# this returns something like:

 #     Dimensions:      (lat: 600, lon: 672, time: 37)
 #     Coordinates:
 #     * lat          (lat) float32 -3.9791672 -3.9375012 ... 20.9375 20.979166
 #     * lon          (lon) float32 -60.979168 -60.9375 ... -33.0625 -33.020832
 #     * time         (time) datetime64[ns] 2010-05-19 2010-05-20 ... 2010-06-24
 #     Data variables:
 #       variable_name  (time, lat, lon) float32 dask.array<shape=(37, 600, 672), 
 #         chunksize=(37, 600, 672)>

 # I normally use the 'sel' method to slice the xarray object, like below:

Sliced_Xarray_DataArray = Xarray_DataArray.sel({'lat':slice(-10, -9),
                                                'lon':slice(-170, -169)                  
                                                })


 # but since, Xarray does not possess a proper way to check the slice, I usually have to do the following:

 if Sliced_Xarray_DataArray.to_dataframe().empty():
    print('is empty. Nothing to aggregate')

 else:
    Aggregated_value =  Aggregation_function(Sliced_Xarray_DataArray)

    print('continuing with the analysis')


 #    ... continue

如果有任何建议,我将不胜感激。

感谢您抽出宝贵时间,希望尽快收到您的来信。

此致,

菲利普·R·莱尔

【问题讨论】:

标签: python-3.x pandas python-xarray netcdf4


【解决方案1】:

您可以很容易地检查结果切片中变量的大小是否为 0:

print(Sliced_Xarray_DataArray.time.size)
if Sliced_Xarray_DataArray.time.size == 0:
    print('is empty. Nothing to aggregate')
else:
    print('not empty. Go aggregate')

您的任何坐标变量以及我们的其他变量都可以作为Sliced_Xarray_DataArray 中的属性访问,因此在您的示例中,您可以检查lat、lon 或time 的大小。

【讨论】:

  • 我明白了。谢谢克里斯。关于坐标变量,使用它们检查数据的唯一问题是我需要一次验证一个,以便知道我是否有要聚合的数据,这会减慢我的算法。此外,它会使阅读和再现性变得更糟。您建议的第一个解决方案既干净又简单。我会采纳的。如果您愿意,请在 GitHub 中查看我的算法。它在时空维度上对几何图形进行匹配操作。随意使用。这是链接:“github.com/PhilipeRLeal/time_space_aggregations”
猜你喜欢
  • 2021-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-02
  • 2018-06-20
  • 2011-02-27
  • 2015-04-28
  • 2019-12-20
相关资源
最近更新 更多