Skip to content

Commit b65ce86

Browse files
huardshoyer
authored andcommitted
Honor keep_attrs in DataArray.quantile (#3305)
* Added `keep_attrs` argument to Variable.quantile. TestDataArray.test_quantile now checks for attributes in output. * black * updated whats new. * removed vestigial comment. Switched default Variable.quantile keep_attrs to False.
1 parent 1ce9105 commit b65ce86

File tree

4 files changed

+30
-16
lines changed

4 files changed

+30
-16
lines changed

doc/whats-new.rst

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ Breaking changes
2626

2727
- The ``isel_points`` and ``sel_points`` methods are removed, having been deprecated
2828
since v0.10.0. These are redundant with the ``isel`` / ``sel`` methods.
29-
See :ref:`vectorized_indexing` for the details
30-
By `Maximilian Roos <https://github.com/max-sixty>`_
29+
See :ref:`vectorized_indexing` for the details
30+
By `Maximilian Roos <https://github.com/max-sixty>`_
3131
- The ``inplace`` kwarg for public methods now raises an error, having been deprecated
3232
since v0.11.0.
3333
By `Maximilian Roos <https://github.com/max-sixty>`_
@@ -52,12 +52,12 @@ Breaking changes
5252
error in a later release.
5353

5454
(:issue:`3250`) by `Guido Imperiale <https://github.com/crusaderky>`_.
55-
- :py:meth:`~Dataset.to_dataset` requires ``name`` to be passed as a kwarg (previously ambiguous
55+
- :py:meth:`~Dataset.to_dataset` requires ``name`` to be passed as a kwarg (previously ambiguous
5656
positional arguments were deprecated)
5757
- Reindexing with variables of a different dimension now raise an error (previously deprecated)
58-
- :py:func:`~xarray.broadcast_array` is removed (previously deprecated in favor of
58+
- :py:func:`~xarray.broadcast_array` is removed (previously deprecated in favor of
5959
:py:func:`~xarray.broadcast`)
60-
- :py:meth:`~Variable.expand_dims` is removed (previously deprecated in favor of
60+
- :py:meth:`~Variable.expand_dims` is removed (previously deprecated in favor of
6161
:py:meth:`~Variable.set_dims`)
6262

6363
New functions/methods
@@ -90,7 +90,7 @@ New functions/methods
9090
and `Maximilian Roos <https://github.com/max-sixty>`_.
9191

9292
- Added :py:meth:`DataArray.broadcast_like` and :py:meth:`Dataset.broadcast_like`.
93-
By `Deepak Cherian <https://github.com/dcherian>`_ and `David Mertz
93+
By `Deepak Cherian <https://github.com/dcherian>`_ and `David Mertz
9494
<http://github.com/DavidMertz>`_.
9595

9696
- Dataset plotting API for visualizing dependencies between two `DataArray`s!
@@ -131,14 +131,14 @@ Enhancements
131131
:py:meth:`DataArray.set_index`, as well are more specific error messages
132132
when the user passes invalid arguments (:issue:`3176`).
133133
By `Gregory Gundersen <https://github.com/gwgundersen>`_.
134-
134+
135135
- :py:func:`filter_by_attrs` now filters the coordinates as well as the variables. By `Spencer Jones <https://github.com/cspencerjones>`_.
136136

137137
Bug fixes
138138
~~~~~~~~~
139139

140-
- Improve "missing dimensions" error message for :py:func:`~xarray.apply_ufunc`
141-
(:issue:`2078`).
140+
- Improve "missing dimensions" error message for :py:func:`~xarray.apply_ufunc`
141+
(:issue:`2078`).
142142
By `Rick Russotto <https://github.com/rdrussotto>`_.
143143
- :py:meth:`~xarray.DataArray.assign_coords` now supports dictionary arguments
144144
(:issue:`3231`).
@@ -170,6 +170,8 @@ Bug fixes
170170
dask compute (:issue:`3237`). By `Ulrich Herter <https://github.com/ulijh>`_.
171171
- Plots in 2 dimensions (pcolormesh, contour) now allow to specify levels as numpy
172172
array (:issue:`3284`). By `Mathias Hauser <https://github.com/mathause>`_.
173+
- Fixed bug in :meth:`DataArray.quantile` failing to keep attributes when
174+
`keep_attrs` was True (:issue:`3304`). By David Huard <https://github.com/huard>`_.
173175

174176
.. _whats-new.0.12.3:
175177

xarray/core/dataset.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4831,7 +4831,10 @@ def quantile(
48314831
# the former is often more efficient
48324832
reduce_dims = None
48334833
variables[name] = var.quantile(
4834-
q, dim=reduce_dims, interpolation=interpolation
4834+
q,
4835+
dim=reduce_dims,
4836+
interpolation=interpolation,
4837+
keep_attrs=keep_attrs,
48354838
)
48364839

48374840
else:

xarray/core/variable.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1592,7 +1592,7 @@ def no_conflicts(self, other):
15921592
"""
15931593
return self.broadcast_equals(other, equiv=duck_array_ops.array_notnull_equiv)
15941594

1595-
def quantile(self, q, dim=None, interpolation="linear"):
1595+
def quantile(self, q, dim=None, interpolation="linear", keep_attrs=None):
15961596
"""Compute the qth quantile of the data along the specified dimension.
15971597
15981598
Returns the qth quantiles(s) of the array elements.
@@ -1615,6 +1615,10 @@ def quantile(self, q, dim=None, interpolation="linear"):
16151615
* higher: ``j``.
16161616
* nearest: ``i`` or ``j``, whichever is nearest.
16171617
* midpoint: ``(i + j) / 2``.
1618+
keep_attrs : bool, optional
1619+
If True, the variable's attributes (`attrs`) will be copied from
1620+
the original object to the new one. If False (default), the new
1621+
object will be returned without attributes.
16181622
16191623
Returns
16201624
-------
@@ -1623,7 +1627,7 @@ def quantile(self, q, dim=None, interpolation="linear"):
16231627
is a scalar. If multiple percentiles are given, first axis of
16241628
the result corresponds to the quantile and a quantile dimension
16251629
is added to the return array. The other dimensions are the
1626-
dimensions that remain after the reduction of the array.
1630+
dimensions that remain after the reduction of the array.
16271631
16281632
See Also
16291633
--------
@@ -1651,14 +1655,19 @@ def quantile(self, q, dim=None, interpolation="linear"):
16511655
axis = None
16521656
new_dims = []
16531657

1654-
# only add the quantile dimension if q is array like
1658+
# Only add the quantile dimension if q is array-like
16551659
if q.ndim != 0:
16561660
new_dims = ["quantile"] + new_dims
16571661

16581662
qs = np.nanpercentile(
16591663
self.data, q * 100.0, axis=axis, interpolation=interpolation
16601664
)
1661-
return Variable(new_dims, qs)
1665+
1666+
if keep_attrs is None:
1667+
keep_attrs = _get_keep_attrs(default=False)
1668+
attrs = self._attrs if keep_attrs else None
1669+
1670+
return Variable(new_dims, qs, attrs)
16621671

16631672
def rank(self, dim, pct=False):
16641673
"""Ranks the data.

xarray/tests/test_dataarray.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2333,17 +2333,17 @@ def test_reduce_out(self):
23332333
with pytest.raises(TypeError):
23342334
orig.mean(out=np.ones(orig.shape))
23352335

2336-
# skip due to bug in older versions of numpy.nanpercentile
23372336
def test_quantile(self):
23382337
for q in [0.25, [0.50], [0.25, 0.75]]:
23392338
for axis, dim in zip(
23402339
[None, 0, [0], [0, 1]], [None, "x", ["x"], ["x", "y"]]
23412340
):
2342-
actual = self.dv.quantile(q, dim=dim)
2341+
actual = DataArray(self.va).quantile(q, dim=dim, keep_attrs=True)
23432342
expected = np.nanpercentile(
23442343
self.dv.values, np.array(q) * 100, axis=axis
23452344
)
23462345
np.testing.assert_allclose(actual.values, expected)
2346+
assert actual.attrs == self.attrs
23472347

23482348
def test_reduce_keep_attrs(self):
23492349
# Test dropped attrs

0 commit comments

Comments
 (0)