Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(fix): don't handle time-dtypes as extension arrays in from_dataframe #9042

Merged
merged 8 commits into from
Jun 11, 2024
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ Deprecations

Bug fixes
~~~~~~~~~
- Preserve conversion of timezone-aware pandas Datetime arrays to numpy object arrays
(:issue:`9026`, :pull:`9042`).
By `Ilan Gold <https://github.com/ilan-gold>`_.

- :py:meth:`DataArrayResample.interpolate` and :py:meth:`DatasetResample.interpolate` method now
support aribtrary kwargs such as ``order`` for polynomial interpolation. (:issue:`8762`).
Expand Down
22 changes: 22 additions & 0 deletions properties/test_pandas_roundtrip.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@
)


datetime_with_tz_strategy = st.datetimes(timezones=st.timezones())
dataframe_strategy = pdst.data_frames(
[
pdst.column("datetime_col", elements=datetime_with_tz_strategy),
pdst.column("other_col", elements=st.integers()),
],
index=pdst.range_indexes(min_size=1, max_size=10),
)


@st.composite
def datasets_1d_vars(draw) -> xr.Dataset:
"""Generate datasets with only 1D variables
Expand Down Expand Up @@ -98,3 +108,15 @@ def test_roundtrip_pandas_dataframe(df) -> None:
roundtripped = arr.to_pandas()
pd.testing.assert_frame_equal(df, roundtripped)
xr.testing.assert_identical(arr, roundtripped.to_xarray())


@given(df=dataframe_strategy)
def test_roundtrip_pandas_dataframe_datetime(df) -> None:
# Need to name the indexes, otherwise Xarray names them 'dim_0', 'dim_1'.
df.index.name = "rows"
df.columns.name = "cols"
dataset = xr.Dataset.from_dataframe(df)
roundtripped = dataset.to_dataframe()
roundtripped.columns.name = "cols" # why?
dcherian marked this conversation as resolved.
Show resolved Hide resolved
pd.testing.assert_frame_equal(df, roundtripped)
dcherian marked this conversation as resolved.
Show resolved Hide resolved
xr.testing.assert_identical(dataset, roundtripped.to_xarray())
4 changes: 3 additions & 1 deletion xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -7420,7 +7420,9 @@ def from_dataframe(cls, dataframe: pd.DataFrame, sparse: bool = False) -> Self:
arrays = []
extension_arrays = []
for k, v in dataframe.items():
if not is_extension_array_dtype(v):
if not is_extension_array_dtype(v) or isinstance(
v.array, (pd.arrays.DatetimeArray, pd.arrays.TimedeltaArray)
):
arrays.append((k, np.asarray(v)))
else:
extension_arrays.append((k, v))
Expand Down
Loading