Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,9 @@ Deprecations

Bug Fixes
~~~~~~~~~
- Preserve indexed coordinates whose name differs from their dimension as
columns in :py:meth:`Dataset.to_dataframe` (:issue:`10851`).
By `Yuvraj Lamba <https://github.com/uvcode01-max>`_.
- Weighted variance, standard deviation and sums of squared deviations now
use conjugated deviations for complex data, matching unweighted reductions
and correcting weighted self-correlation.
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,7 @@ Noice = "Noice"
Hax = "Hax"
Yau = "Yau"
whn = "whn"
Lamba = "Lamba"

# Tests
Ome = "Ome"
Expand Down
10 changes: 7 additions & 3 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -7632,9 +7632,13 @@ def _to_dataframe(self, ordered_dims: Mapping[Any, int]):
from xarray.core.extension_array import PandasExtensionArray

# All and only non-index arrays (whether data or coordinates) should
# become columns in the output DataFrame. Excluding indexes rather
# than dims handles the case of a MultiIndex along a single dimension.
columns_in_order = [k for k in self.variables if k not in self.xindexes]
# become columns in the output DataFrame. Excluding only the dimensions
# and index levels ensures that indexed coordinates whose name differs
# from their dimension are preserved as columns (GH10851).
index_names = set(ordered_dims) | set(
self.coords.to_index([*ordered_dims]).names
)
columns_in_order = [k for k in self.variables if k not in index_names]
non_extension_array_columns = [
k
for k in columns_in_order
Expand Down
25 changes: 25 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -5659,6 +5659,31 @@ def test_to_and_from_dataframe(self) -> None:
expected = pd.DataFrame([[]], index=idx)
assert expected.equals(actual), (expected, actual)

def test_to_dataframe_indexed_coord_differing_name(self) -> None:
# GH10851: Index coordinates whose name differs from dimension name
# should still be included in DataFrame columns.
ds = Dataset(
data_vars={"temp": (["time", "pos"], np.array([[5, 10, 15, 20, 25]]))},
coords={
"pf": ("pos", [1.0, 2.0, 4.2, 8.0, 10.0]),
"time": ("time", [pd.to_datetime("2025-01-01")]),
},
).set_xindex("pf")

df = ds.to_dataframe()
assert "pf" in df.columns
assert "temp" in df.columns
np.testing.assert_array_equal(df["pf"].values, [1.0, 2.0, 4.2, 8.0, 10.0])

# Verify dimension index coordinate is still excluded from columns
ds_dim = Dataset(
data_vars={"temp": (["x"], [1, 2, 3])},
coords={"x": ("x", [10, 20, 30])},
)
df_dim = ds_dim.to_dataframe()
assert "temp" in df_dim.columns
assert "x" not in df_dim.columns

@requires_sparse
def test_to_dataframe_sparse_crash_regression(self) -> None:
# `Dataset.to_dataframe()` used to unconditionally call `.values` on
Expand Down
Loading