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

Save to excel #262

Merged
merged 17 commits into from
Oct 2, 2023
Merged
Show file tree
Hide file tree
Changes from 11 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
1 change: 1 addition & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ New features and enhancements
* Added the ability to search for simulations that reach a given warming level. (:pull:`251`).
* ``xs.spatial_mean`` now accepts the ``region="global"`` keyword to perform a global average (:issue:`94`, :pull:`260`).
* ``xs.spatial_mean`` with ``method='xESMF'`` will also automatically segmentize polygons (down to a 1° resolution) to ensure a correct average (:pull:`260`).
* ``xs.io.save_to_table`` and ``xs.io.to_table`` to transform datasets and arrays to DataFrames, but with support for multi-columns and multi-sheets.

Breaking changes
^^^^^^^^^^^^^^^^
Expand Down
50 changes: 50 additions & 0 deletions tests/test_io.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import numpy as np
import pytest
import xarray as xr

import xscen as xs

Expand Down Expand Up @@ -66,3 +67,52 @@ def test_variables(self, datablock_3d):
for v in ds_ch.data_vars:
for dim, chunks in zip(list(ds.dims), ds_ch[v].chunks):
assert chunks[0] == new_chunks[v][dim]


class TestToTable:
ds = xs.utils.unstack_dates(
xr.merge(
[
xs.testing.datablock_3d(
np.random.random_sample((20, 3, 2)),
v,
"lon",
0,
"lat",
0,
1,
1,
"1993-01-01",
"QS-JAN",
)
for v in ["tas", "pr", "snw"]
]
)
.stack(site=["lat", "lon"])
.reset_index("site")
.assign_coords(site=list("abcdef"))
).transpose("season", "time", "site")

def test_normal(self):
# Default
tab = xs.io.to_table(self.ds)
assert tab.shape == (120, 5) # 3 vars + 2 aux coords
assert tab.columns.names == ["variable"]
assert tab.index.names == ["season", "time", "site"]
# Season order is chronological, rather than alphabetical
np.testing.assert_array_equal(
tab.xs("1993", level="time")
.xs("a", level="site")
.index.get_level_values("season"),
["JFM", "AMJ", "JAS", "OND"],
)

# Variable in the index, thus no coords
tab = xs.io.to_table(
self.ds, row=["time", "variable"], column=["season", "site"], coords=False
)
assert tab.shape == (15, 24)
assert tab.columns.names == ["season", "site"]
np.testing.assert_array_equal(
tab.loc[("1993", "pr"), ("JFM",)], self.ds.pr.sel(time="1993", season="JFM")
)
Loading
Loading