|
| 1 | +from distutils.version import LooseVersion |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +import pytest |
| 5 | + |
| 6 | +import pandas.util._test_decorators as td |
| 7 | + |
| 8 | +import pandas as pd |
| 9 | +from pandas import DataFrame, Series |
| 10 | +import pandas._testing as tm |
| 11 | + |
| 12 | +try: |
| 13 | + import xarray |
| 14 | + |
| 15 | + _XARRAY_INSTALLED = True |
| 16 | +except ImportError: |
| 17 | + _XARRAY_INSTALLED = False |
| 18 | + |
| 19 | + |
| 20 | +class TestDataFrameToXArray: |
| 21 | + @pytest.mark.skipif( |
| 22 | + not _XARRAY_INSTALLED |
| 23 | + or _XARRAY_INSTALLED |
| 24 | + and LooseVersion(xarray.__version__) < LooseVersion("0.10.0"), |
| 25 | + reason="xarray >= 0.10.0 required", |
| 26 | + ) |
| 27 | + def test_to_xarray_index_types(self, indices): |
| 28 | + if isinstance(indices, pd.MultiIndex): |
| 29 | + pytest.skip("MultiIndex is tested separately") |
| 30 | + if len(indices) == 0: |
| 31 | + pytest.skip("Test doesn't make sense for empty index") |
| 32 | + |
| 33 | + from xarray import Dataset |
| 34 | + |
| 35 | + df = DataFrame( |
| 36 | + { |
| 37 | + "a": list("abc"), |
| 38 | + "b": list(range(1, 4)), |
| 39 | + "c": np.arange(3, 6).astype("u1"), |
| 40 | + "d": np.arange(4.0, 7.0, dtype="float64"), |
| 41 | + "e": [True, False, True], |
| 42 | + "f": pd.Categorical(list("abc")), |
| 43 | + "g": pd.date_range("20130101", periods=3), |
| 44 | + "h": pd.date_range("20130101", periods=3, tz="US/Eastern"), |
| 45 | + } |
| 46 | + ) |
| 47 | + |
| 48 | + df.index = indices[:3] |
| 49 | + df.index.name = "foo" |
| 50 | + df.columns.name = "bar" |
| 51 | + result = df.to_xarray() |
| 52 | + assert result.dims["foo"] == 3 |
| 53 | + assert len(result.coords) == 1 |
| 54 | + assert len(result.data_vars) == 8 |
| 55 | + tm.assert_almost_equal(list(result.coords.keys()), ["foo"]) |
| 56 | + assert isinstance(result, Dataset) |
| 57 | + |
| 58 | + # idempotency |
| 59 | + # datetimes w/tz are preserved |
| 60 | + # column names are lost |
| 61 | + expected = df.copy() |
| 62 | + expected["f"] = expected["f"].astype(object) |
| 63 | + expected.columns.name = None |
| 64 | + tm.assert_frame_equal( |
| 65 | + result.to_dataframe(), expected, |
| 66 | + ) |
| 67 | + |
| 68 | + @td.skip_if_no("xarray", min_version="0.7.0") |
| 69 | + def test_to_xarray(self): |
| 70 | + from xarray import Dataset |
| 71 | + |
| 72 | + df = DataFrame( |
| 73 | + { |
| 74 | + "a": list("abc"), |
| 75 | + "b": list(range(1, 4)), |
| 76 | + "c": np.arange(3, 6).astype("u1"), |
| 77 | + "d": np.arange(4.0, 7.0, dtype="float64"), |
| 78 | + "e": [True, False, True], |
| 79 | + "f": pd.Categorical(list("abc")), |
| 80 | + "g": pd.date_range("20130101", periods=3), |
| 81 | + "h": pd.date_range("20130101", periods=3, tz="US/Eastern"), |
| 82 | + } |
| 83 | + ) |
| 84 | + |
| 85 | + df.index.name = "foo" |
| 86 | + result = df[0:0].to_xarray() |
| 87 | + assert result.dims["foo"] == 0 |
| 88 | + assert isinstance(result, Dataset) |
| 89 | + |
| 90 | + # available in 0.7.1 |
| 91 | + # MultiIndex |
| 92 | + df.index = pd.MultiIndex.from_product([["a"], range(3)], names=["one", "two"]) |
| 93 | + result = df.to_xarray() |
| 94 | + assert result.dims["one"] == 1 |
| 95 | + assert result.dims["two"] == 3 |
| 96 | + assert len(result.coords) == 2 |
| 97 | + assert len(result.data_vars) == 8 |
| 98 | + tm.assert_almost_equal(list(result.coords.keys()), ["one", "two"]) |
| 99 | + assert isinstance(result, Dataset) |
| 100 | + |
| 101 | + result = result.to_dataframe() |
| 102 | + expected = df.copy() |
| 103 | + expected["f"] = expected["f"].astype(object) |
| 104 | + expected.columns.name = None |
| 105 | + tm.assert_frame_equal(result, expected, check_index_type=False) |
| 106 | + |
| 107 | + |
| 108 | +class TestSeriesToXArray: |
| 109 | + @pytest.mark.skipif( |
| 110 | + not _XARRAY_INSTALLED |
| 111 | + or _XARRAY_INSTALLED |
| 112 | + and LooseVersion(xarray.__version__) < LooseVersion("0.10.0"), |
| 113 | + reason="xarray >= 0.10.0 required", |
| 114 | + ) |
| 115 | + def test_to_xarray_index_types(self, indices): |
| 116 | + if isinstance(indices, pd.MultiIndex): |
| 117 | + pytest.skip("MultiIndex is tested separately") |
| 118 | + |
| 119 | + from xarray import DataArray |
| 120 | + |
| 121 | + s = Series(range(len(indices)), index=indices) |
| 122 | + s.index.name = "foo" |
| 123 | + result = s.to_xarray() |
| 124 | + repr(result) |
| 125 | + assert len(result) == len(indices) |
| 126 | + assert len(result.coords) == 1 |
| 127 | + tm.assert_almost_equal(list(result.coords.keys()), ["foo"]) |
| 128 | + assert isinstance(result, DataArray) |
| 129 | + |
| 130 | + # idempotency |
| 131 | + tm.assert_series_equal(result.to_series(), s, check_index_type=False) |
| 132 | + |
| 133 | + @td.skip_if_no("xarray", min_version="0.7.0") |
| 134 | + def test_to_xarray(self): |
| 135 | + from xarray import DataArray |
| 136 | + |
| 137 | + s = Series([], dtype=object) |
| 138 | + s.index.name = "foo" |
| 139 | + result = s.to_xarray() |
| 140 | + assert len(result) == 0 |
| 141 | + assert len(result.coords) == 1 |
| 142 | + tm.assert_almost_equal(list(result.coords.keys()), ["foo"]) |
| 143 | + assert isinstance(result, DataArray) |
| 144 | + |
| 145 | + s = Series(range(6)) |
| 146 | + s.index.name = "foo" |
| 147 | + s.index = pd.MultiIndex.from_product( |
| 148 | + [["a", "b"], range(3)], names=["one", "two"] |
| 149 | + ) |
| 150 | + result = s.to_xarray() |
| 151 | + assert len(result) == 2 |
| 152 | + tm.assert_almost_equal(list(result.coords.keys()), ["one", "two"]) |
| 153 | + assert isinstance(result, DataArray) |
| 154 | + tm.assert_series_equal(result.to_series(), s) |
0 commit comments