本文整理汇总了Python中xarray.Dataset.sel方法的典型用法代码示例。如果您正苦于以下问题:Python Dataset.sel方法的具体用法?Python Dataset.sel怎么用?Python Dataset.sel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xarray.Dataset
的用法示例。
在下文中一共展示了Dataset.sel方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _normalize_inverted_lat
# 需要导入模块: from xarray import Dataset [as 别名]
# 或者: from xarray.Dataset import sel [as 别名]
def _normalize_inverted_lat(ds: xr.Dataset) -> xr.Dataset:
"""
In case the latitude decreases, invert it
:param ds: some xarray dataset
:return: a normalized xarray dataset
"""
try:
if _lat_inverted(ds.lat):
ds = ds.sel(lat=slice(None, None, -1))
except AttributeError:
# The dataset doesn't have 'lat', probably not geospatial
pass
except ValueError:
# The dataset still has an ND 'lat' array
pass
return ds
示例2: _resample_dataset
# 需要导入模块: from xarray import Dataset [as 别名]
# 或者: from xarray.Dataset import sel [as 别名]
def _resample_dataset(ds_master: xr.Dataset, ds_replica: xr.Dataset, method_us: int, method_ds: int, monitor: Monitor) -> xr.Dataset:
"""
Resample replica onto the grid of the master.
This does spatial resampling the whole dataset, e.g., all
variables in the replica dataset.
This method works only if both datasets have (time, lat, lon) dimensions.
Note that dataset attributes are not propagated due to currently undecided CDM attributes' set.
:param ds_master: xr.Dataset whose lat/lon coordinates are used as the resampling grid
:param ds_replica: xr.Dataset that will be resampled on the masters' grid
:param method_us: Interpolation method for upsampling, see resampling.py
:param method_ds: Interpolation method for downsampling, see resampling.py
:param monitor: a progress monitor.
:return: xr.Dataset The resampled replica dataset
"""
# Find lat/lon bounds of the intersection of master and replica grids. The
# bounds should fall on pixel boundaries for both spatial dimensions for
# both datasets
lat_min, lat_max = _find_intersection(ds_master['lat'].values,
ds_replica['lat'].values,
global_bounds=(-90, 90))
lon_min, lon_max = _find_intersection(ds_master['lon'].values,
ds_replica['lon'].values,
global_bounds=(-180, 180))
# Subset replica dataset and master grid. We're not using here the subset
# operation, because the subset operation may produce datasets that cross
# the anti-meridian by design. However, such a disjoint dataset can not be
# resampled using our current resampling methods.
lat_slice = slice(lat_min, lat_max)
lon_slice = slice(lon_min, lon_max)
lon = ds_master['lon'].sel(lon=lon_slice)
lat = ds_master['lat'].sel(lat=lat_slice)
ds_replica = ds_replica.sel(lon=lon_slice, lat=lat_slice)
# Don't do anything if datasets already have the same spatial definition
if _grids_equal(ds_master, ds_replica):
return ds_replica
with monitor.starting("coregister dataset", len(ds_replica.data_vars)):
kwargs = {'lon': lon, 'lat': lat, 'method_us': method_us, 'method_ds': method_ds, 'parent_monitor': monitor}
retset = ds_replica.apply(_resample_array, keep_attrs=True, **kwargs)
return adjust_spatial_attrs(retset)
示例3: subset_temporal_impl
# 需要导入模块: from xarray import Dataset [as 别名]
# 或者: from xarray.Dataset import sel [as 别名]
def subset_temporal_impl(ds: xr.Dataset,
time_range: Tuple[datetime, datetime]) -> xr.Dataset:
"""
Do a temporal subset of the dataset.
:param ds: Dataset or dataframe to subset
:param time_range: Time range to select
:return: Subset dataset
"""
# If it can be selected, go ahead
try:
# noinspection PyTypeChecker
time_slice = slice(time_range[0], time_range[1])
indexers = {'time': time_slice}
return ds.sel(**indexers)
except TypeError:
raise ValueError('Time subset operation expects a dataset with the'
' time coordinate of type datetime64[ns], but received'
' {}. Running the normalize operation on this'
' dataset may help'.format(ds.time.dtype))
示例4: navtimeseries
# 需要导入模块: from xarray import Dataset [as 别名]
# 或者: from xarray.Dataset import sel [as 别名]
def navtimeseries(nav: xarray.Dataset):
if not isinstance(nav, xarray.Dataset):
return
svs = nav.sv.values
if cartopy is not None:
ax = figure().gca(projection=cartopy.crs.PlateCarree())
ax.add_feature(cpf.LAND)
ax.add_feature(cpf.OCEAN)
ax.add_feature(cpf.COASTLINE)
ax.add_feature(cpf.BORDERS, linestyle=':')
else:
ax = figure().gca()
for sv in svs:
if sv[0] == 'S':
lat, lon, alt = pm.ecef2geodetic(nav.sel(sv=sv)['X'].dropna(dim='time', how='all'),
nav.sel(sv=sv)['Y'].dropna(
dim='time', how='all'),
nav.sel(sv=sv)['Z'].dropna(dim='time', how='all'))
if ((alt < 35.7e6) | (alt > 35.9e6)).any():
logging.warning('unrealistic geostationary satellite altitudes')
if ((lat < -1) | (lat > 1)).any():
logging.warning('unrealistic geostationary satellite latitudes')
elif sv[0] == 'R':
lat, lon, alt = pm.ecef2geodetic(nav.sel(sv=sv)['X'].dropna(dim='time', how='all'),
nav.sel(sv=sv)['Y'].dropna(
dim='time', how='all'),
nav.sel(sv=sv)['Z'].dropna(dim='time', how='all'))
if ((alt < 19.0e6) | (alt > 19.4e6)).any():
logging.warning('unrealistic GLONASS satellite altitudes')
if ((lat < -67) | (lat > 67)).any():
logging.warning('GLONASS inclination ~ 65 degrees')
elif sv[0] == 'G':
ecef = keplerian2ecef(nav.sel(sv=sv))
lat, lon, alt = pm.ecef2geodetic(*ecef)
if ((alt < 19.4e6) | (alt > 21.0e6)).any():
logging.warning('unrealistic GPS satellite altitudes')
if ((lat < -57) | (lat > 57)).any():
logging.warning('GPS inclination ~ 55 degrees')
elif sv[0] == 'E':
ecef = keplerian2ecef(nav.sel(sv=sv))
lat, lon, alt = pm.ecef2geodetic(*ecef)
if ((alt < 23e6) | (alt > 24e6)).any():
logging.warning('unrealistic Galileo satellite altitudes')
if ((lat < -57) | (lat > 57)).any():
logging.warning('Galileo inclination ~ 56 degrees')
else:
continue
ax.plot(lon, lat, label=sv)
示例5: subset_spatial_impl
# 需要导入模块: from xarray import Dataset [as 别名]
# 或者: from xarray.Dataset import sel [as 别名]
def subset_spatial_impl(ds: xr.Dataset,
region: PolygonLike.TYPE,
mask: bool = True,
monitor: Monitor = Monitor.NONE) -> xr.Dataset:
"""
Do a spatial subset of the dataset
:param ds: Dataset to subset
:param region: Spatial region to subset
:param mask: Should values falling in the bounding box of the polygon but
not the polygon itself be masked with NaN.
:param monitor: optional progress monitor
:return: Subset dataset
"""
# Validate whether lat and lon exists.
if not hasattr(ds, 'lon') or not hasattr(ds, 'lat'):
raise ValidationError('Cannot apply regional subset. No (valid) geocoding found.')
if hasattr(ds, 'lon') and len(ds.lon.shape) != 1 \
or hasattr(ds, 'lat') and len(ds.lat.shape) != 1:
raise ValidationError('Geocoding not recognised. Variables "lat" and/or "lon" have more than one dimension.')
monitor.start('Subset', 10)
# Validate input
try:
polygon = PolygonLike.convert(region)
except BaseException as e:
raise e
extents, explicit_coords = get_extents(region)
lon_min, lat_min, lon_max, lat_max = extents
# Validate the bounding box
if (not (-90 <= lat_min <= 90)) or \
(not (-90 <= lat_max <= 90)) or \
(not (-180 <= lon_min <= 180)) or \
(not (-180 <= lon_max <= 180)):
raise ValidationError('Provided polygon extends outside of geo-spatial bounds.'
' Latitudes should be from -90 to 90 and longitudes from -180 to 180 degrees.')
# Don't do the computationally intensive masking if the provided
# region is a simple box-polygon, for which there will be nothing to
# mask.
simple_polygon = polygon.equals(box(lon_min, lat_min, lon_max, lat_max))
# Pad extents to include crossed pixels
lon_min, lat_min, lon_max, lat_max = _pad_extents(ds, extents)
crosses_antimeridian = (lon_min > lon_max) if explicit_coords else _crosses_antimeridian(polygon)
lat_inverted = _lat_inverted(ds.lat)
if lat_inverted:
lat_index = slice(lat_max, lat_min)
else:
lat_index = slice(lat_min, lat_max)
if crosses_antimeridian and not simple_polygon and mask:
# Unlikely but plausible
raise NotImplementedError('Spatial subsets crossing the anti-meridian'
' are currently implemented for simple,'
' rectangular polygons only, or complex polygons'
' without masking.')
monitor.progress(1)
if crosses_antimeridian:
# Shapely messes up longitudes if the polygon crosses the antimeridian
if not explicit_coords:
lon_min, lon_max = lon_max, lon_min
# Can't perform a simple selection with slice, hence we have to
# construct an appropriate longitude indexer for selection
lon_left_of_idl = slice(lon_min, 180)
lon_right_of_idl = slice(-180, lon_max)
lon_index = xr.concat((ds.lon.sel(lon=lon_right_of_idl),
ds.lon.sel(lon=lon_left_of_idl)), dim='lon')
indexers = {'lon': lon_index, 'lat': lat_index}
retset = ds.sel(**indexers)
# Preserve the original longitude dimension, masking elements that
# do not belong to the polygon with NaN.
with monitor.observing('subset'):
return reset_non_spatial(ds, retset.reindex_like(ds.lon))
lon_slice = slice(lon_min, lon_max)
indexers = {'lat': lat_index, 'lon': lon_slice}
retset = ds.sel(**indexers)
if len(retset.lat) == 0 or len(retset.lon) == 0:
# Empty return dataset => region out of dataset bounds
raise ValueError("Can not select a region outside dataset boundaries.")
if not mask or simple_polygon or explicit_coords:
# The polygon doesn't cross the anti-meridian, it is a simple box -> Use a simple slice
with monitor.observing('subset'):
return reset_non_spatial(ds, retset)
# Create the mask array. The result of this is a lon/lat DataArray where
# all pixels falling in the region or on its boundary are denoted with True
#.........这里部分代码省略.........