當前位置: 首頁>>代碼示例>>Python>>正文


Python xarray.DataArray方法代碼示例

本文整理匯總了Python中xarray.DataArray方法的典型用法代碼示例。如果您正苦於以下問題:Python xarray.DataArray方法的具體用法?Python xarray.DataArray怎麽用?Python xarray.DataArray使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在xarray的用法示例。


在下文中一共展示了xarray.DataArray方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: monthly_mean_ts

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import DataArray [as 別名]
def monthly_mean_ts(arr):
    """Convert a sub-monthly time-series into one of monthly means.

    Also drops any months with no data in the original DataArray.

    Parameters
    ----------
    arr : xarray.DataArray
        Timeseries of sub-monthly temporal resolution data

    Returns
    -------
    xarray.DataArray
        Array resampled to comprise monthly means

    See Also
    --------
    monthly_mean_at_each_ind : Copy monthly means to each submonthly time

    """
    return arr.resample(
        **{TIME_STR: '1M'}, restore_coord_dims=True
    ).mean(TIME_STR).dropna(TIME_STR) 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:25,代碼來源:times.py

示例2: monthly_mean_at_each_ind

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import DataArray [as 別名]
def monthly_mean_at_each_ind(monthly_means, sub_monthly_timeseries):
    """Copy monthly mean over each time index in that month.

    Parameters
    ----------
    monthly_means : xarray.DataArray
        array of monthly means
    sub_monthly_timeseries : xarray.DataArray
        array of a timeseries at sub-monthly time resolution

    Returns
    -------
    xarray.DataArray with eath monthly mean value from `monthly_means` repeated
    at each time within that month from `sub_monthly_timeseries`

    See Also
    --------
    monthly_mean_ts : Create timeseries of monthly mean values
    """
    time = monthly_means[TIME_STR]
    start = time.indexes[TIME_STR][0].replace(day=1, hour=0)
    end = time.indexes[TIME_STR][-1]
    new_indices = pd.date_range(start=start, end=end, freq='MS')
    arr_new = monthly_means.reindex(time=new_indices, method='backfill')
    return arr_new.reindex_like(sub_monthly_timeseries, method='pad') 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:27,代碼來源:times.py

示例3: extract_months

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import DataArray [as 別名]
def extract_months(time, months):
    """Extract times within specified months of the year.

    Parameters
    ----------
    time : xarray.DataArray
         Array of times that can be represented by numpy.datetime64 objects
         (i.e. the year is between 1678 and 2262).
    months : Desired months of the year to include

    Returns
    -------
    xarray.DataArray of the desired times
    """
    inds = _month_conditional(time, months)
    return time.sel(time=inds) 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:18,代碼來源:times.py

示例4: assert_matching_time_coord

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import DataArray [as 別名]
def assert_matching_time_coord(arr1, arr2):
    """Check to see if two DataArrays have the same time coordinate.

    Parameters
    ----------
    arr1 : DataArray or Dataset
        First DataArray or Dataset
    arr2 : DataArray or Dataset
        Second DataArray or Dataset

    Raises
    ------
    ValueError
        If the time coordinates are not identical between the two Datasets
    """
    message = ('Time weights not indexed by the same time coordinate as'
               ' computed data.  This will lead to an improperly computed'
               ' time weighted average.  Exiting.\n'
               'arr1: {}\narr2: {}')
    if not (arr1[TIME_STR].identical(arr2[TIME_STR])):
        raise ValueError(message.format(arr1[TIME_STR], arr2[TIME_STR])) 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:23,代碼來源:times.py

示例5: _bounds_from_array

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import DataArray [as 別名]
def _bounds_from_array(arr, dim_name, bounds_name):
    """Get the bounds of an array given its center values.

    E.g. if lat-lon grid center lat/lon values are known, but not the
    bounds of each grid box.  The algorithm assumes that the bounds
    are simply halfway between each pair of center values.
    """
    # TODO: don't assume needed dimension is in axis=0
    # TODO: refactor to get rid of repetitive code
    spacing = arr.diff(dim_name).values
    lower = xr.DataArray(np.empty_like(arr), dims=arr.dims,
                         coords=arr.coords)
    lower.values[:-1] = arr.values[:-1] - 0.5*spacing
    lower.values[-1] = arr.values[-1] - 0.5*spacing[-1]
    upper = xr.DataArray(np.empty_like(arr), dims=arr.dims,
                         coords=arr.coords)
    upper.values[:-1] = arr.values[:-1] + 0.5*spacing
    upper.values[-1] = arr.values[-1] + 0.5*spacing[-1]
    bounds = xr.concat([lower, upper], dim='bounds')
    return bounds.T 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:22,代碼來源:model.py

示例6: _save_files

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import DataArray [as 別名]
def _save_files(self, data, dtype_out_time):
        """Save the data to netcdf files in direc_out."""
        path = self.path_out[dtype_out_time]
        if not os.path.isdir(self.dir_out):
            os.makedirs(self.dir_out)
        if 'reg' in dtype_out_time:
            try:
                reg_data = xr.open_dataset(path)
            except (EOFError, RuntimeError, IOError):
                reg_data = xr.Dataset()
            reg_data.update(data)
            data_out = reg_data
        else:
            data_out = data
        if isinstance(data_out, xr.DataArray):
            data_out = xr.Dataset({self.name: data_out})
        data_out.to_netcdf(path, engine='netcdf4') 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:19,代碼來源:calc.py

示例7: _maybe_cast_to_float64

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import DataArray [as 別名]
def _maybe_cast_to_float64(da):
    """Cast DataArrays to np.float64 if they are of type np.float32.

    Parameters
    ----------
    da : xr.DataArray
        Input DataArray

    Returns
    -------
    DataArray

    """
    if da.dtype == np.float32:
        logging.warning('Datapoints were stored using the np.float32 datatype.'
                        'For accurate reduction operations using bottleneck, '
                        'datapoints are being cast to the np.float64 datatype.'
                        ' For more information see: https://github.com/pydata/'
                        'xarray/issues/1346')
        return da.astype(np.float64)
    else:
        return da 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:24,代碼來源:data_loader.py

示例8: test_add_uniform_time_weights

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import DataArray [as 別名]
def test_add_uniform_time_weights():
    time = np.array([15, 46, 74])
    data = np.zeros((3))
    ds = xr.DataArray(data,
                      coords=[time],
                      dims=[TIME_STR],
                      name='a').to_dataset()
    units_str = 'days since 2000-01-01 00:00:00'
    cal_str = 'noleap'
    ds[TIME_STR].attrs['units'] = units_str
    ds[TIME_STR].attrs['calendar'] = cal_str

    with pytest.raises(KeyError):
        ds[TIME_WEIGHTS_STR]

    ds = add_uniform_time_weights(ds)
    time_weights_expected = xr.DataArray(
        [1, 1, 1], coords=ds[TIME_STR].coords, name=TIME_WEIGHTS_STR)
    time_weights_expected.attrs['units'] = 'days'
    assert ds[TIME_WEIGHTS_STR].identical(time_weights_expected) 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:22,代碼來源:test_utils_times.py

示例9: test_ensure_time_as_index_with_change

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import DataArray [as 別名]
def test_ensure_time_as_index_with_change():
    # Time bounds array doesn't index time initially, which gets fixed.
    arr = xr.DataArray([-93], dims=[TIME_STR], coords={TIME_STR: [3]})
    arr[TIME_STR].attrs['units'] = 'days since 2000-01-01 00:00:00'
    arr[TIME_STR].attrs['calendar'] = 'standard'
    ds = arr.to_dataset(name='a')
    ds.coords[TIME_WEIGHTS_STR] = xr.DataArray(
        [1], dims=[TIME_STR], coords={TIME_STR: arr[TIME_STR]}
    )
    ds.coords[TIME_BOUNDS_STR] = xr.DataArray(
        [[3.5, 4.5]], dims=[TIME_STR, BOUNDS_STR],
        coords={TIME_STR: arr[TIME_STR]}
    )
    ds = ds.isel(**{TIME_STR: 0})
    actual = ensure_time_as_index(ds)
    expected = arr.to_dataset(name='a')
    expected.coords[TIME_WEIGHTS_STR] = xr.DataArray(
        [1], dims=[TIME_STR], coords={TIME_STR: arr[TIME_STR]}
    )
    expected.coords[TIME_BOUNDS_STR] = xr.DataArray(
        [[3.5, 4.5]], dims=[TIME_STR, BOUNDS_STR],
        coords={TIME_STR: arr[TIME_STR]}
        )
    xr.testing.assert_identical(actual, expected) 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:26,代碼來源:test_utils_times.py

示例10: test_yearly_average_no_mask

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import DataArray [as 別名]
def test_yearly_average_no_mask():
    times = pd.to_datetime(['2000-06-01', '2000-06-15',
                            '2001-07-04', '2001-10-01', '2001-12-31',
                            '2004-01-01'])
    arr = xr.DataArray(np.random.random((len(times),)),
                       dims=[TIME_STR], coords={TIME_STR: times})
    dt = arr.copy(deep=True)
    dt.values = np.random.random((len(times),))

    actual = yearly_average(arr, dt)

    yr2000 = (arr[0]*dt[0] + arr[1]*dt[1]) / (dt[0] + dt[1])
    yr2001 = ((arr[2]*dt[2] + arr[3]*dt[3] + arr[4]*dt[4]) /
              (dt[2] + dt[3] + dt[4]))
    yr2004 = arr[-1]
    yrs_coord = [2000, 2001, 2004]
    yr_avgs = np.array([yr2000, yr2001, yr2004])
    desired = xr.DataArray(yr_avgs, dims=['year'], coords={'year': yrs_coord})
    xr.testing.assert_allclose(actual, desired) 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:21,代碼來源:test_utils_times.py

示例11: test_yearly_average_masked_data

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import DataArray [as 別名]
def test_yearly_average_masked_data():
    times = pd.to_datetime(['2000-06-01', '2000-06-15',
                            '2001-07-04', '2001-10-01', '2001-12-31',
                            '2004-01-01'])
    arr = xr.DataArray(np.random.random((len(times),)),
                       dims=[TIME_STR], coords={TIME_STR: times})
    arr[0] = -999
    arr = arr.where(arr != -999)
    dt = arr.copy(deep=True)
    dt.values = np.random.random((len(times),))

    actual = yearly_average(arr, dt)

    yr2000 = arr[1]
    yr2001 = ((arr[2]*dt[2] + arr[3]*dt[3] + arr[4]*dt[4]) /
              (dt[2] + dt[3] + dt[4]))
    yr2004 = arr[-1]
    yrs_coord = [2000, 2001, 2004]
    yr_avgs = np.array([yr2000, yr2001, yr2004])
    desired = xr.DataArray(yr_avgs, dims=['year'], coords={'year': yrs_coord})
    xr.testing.assert_allclose(actual, desired) 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:23,代碼來源:test_utils_times.py

示例12: ds_time_encoded_cf

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import DataArray [as 別名]
def ds_time_encoded_cf():
    time_bounds = np.array([[0, 31], [31, 59], [59, 90]])
    bounds = np.array([0, 1])
    time = np.array([15, 46, 74])
    data = np.zeros((3))
    ds = xr.DataArray(data,
                      coords=[time],
                      dims=[TIME_STR],
                      name='a').to_dataset()
    ds[TIME_BOUNDS_STR] = xr.DataArray(time_bounds,
                                       coords=[time, bounds],
                                       dims=[TIME_STR, BOUNDS_STR],
                                       name=TIME_BOUNDS_STR)
    units_str = 'days since 2000-01-01 00:00:00'
    cal_str = 'noleap'
    ds[TIME_STR].attrs['units'] = units_str
    ds[TIME_STR].attrs['calendar'] = cal_str
    return ds 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:20,代碼來源:conftest.py

示例13: ds_with_time_bounds

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import DataArray [as 別名]
def ds_with_time_bounds(alt_lat_str, var_name):
    time_bounds = np.array([[0, 31], [31, 59], [59, 90]])
    bounds = np.array([0, 1])
    time = np.array([15, 46, 74])
    data = np.zeros((3, 1, 1))
    lat = [0]
    lon = [0]
    ds = xr.DataArray(data,
                      coords=[time, lat, lon],
                      dims=[TIME_STR, alt_lat_str, LON_STR],
                      name=var_name).to_dataset()
    ds[TIME_BOUNDS_STR] = xr.DataArray(time_bounds,
                                       coords=[time, bounds],
                                       dims=[TIME_STR, BOUNDS_STR],
                                       name=TIME_BOUNDS_STR)
    units_str = 'days since 2000-01-01 00:00:00'
    ds[TIME_STR].attrs['units'] = units_str
    ds[TIME_BOUNDS_STR].attrs['units'] = units_str
    return ds 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:21,代碼來源:test_data_loader.py

示例14: test_sel_var

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import DataArray [as 別名]
def test_sel_var():
    time = np.array([0, 31, 59]) + 15
    data = np.zeros((3))
    ds = xr.DataArray(data,
                      coords=[time],
                      dims=[TIME_STR],
                      name=convection_rain.name).to_dataset()
    condensation_rain_alt_name, = condensation_rain.alt_names
    ds[condensation_rain_alt_name] = xr.DataArray(data, coords=[ds.time])
    result = _sel_var(ds, convection_rain)
    assert result.name == convection_rain.name

    result = _sel_var(ds, condensation_rain)
    assert result.name == condensation_rain.name

    with pytest.raises(LookupError):
        _sel_var(ds, precip) 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:19,代碼來源:test_data_loader.py

示例15: _apply_window

# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import DataArray [as 別名]
def _apply_window(da, dims, window_type='hanning'):
    """Creating windows in dimensions dims."""

    if window_type not in ['hanning']:
        raise NotImplementedError("Only hanning window is supported for now.")

    numpy_win_func = getattr(np, window_type)

    if da.chunks:
        def dask_win_func(n):
            return dsar.from_delayed(
                delayed(numpy_win_func, pure=True)(n),
                (n,), float)
        win_func = dask_win_func
    else:
        win_func = numpy_win_func

    windows = [xr.DataArray(win_func(len(da[d])),
               dims=da[d].dims, coords=da[d].coords) for d in dims]

    return da * reduce(operator.mul, windows[::-1]) 
開發者ID:xgcm,項目名稱:xrft,代碼行數:23,代碼來源:xrft.py


注:本文中的xarray.DataArray方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。