Skip to content

Commit 49f99a6

Browse files
committed
TST/COMPAT: xarray updated to 0.7.1 in conda, adjust to_xarray for
MultiIndex frames with Categoricals
1 parent 528108b commit 49f99a6

File tree

2 files changed

+44
-8
lines changed

2 files changed

+44
-8
lines changed

pandas/core/generic.py

+26-6
Original file line numberDiff line numberDiff line change
@@ -1172,25 +1172,45 @@ def to_xarray(self):
11721172
11731173
Examples
11741174
--------
1175-
>>> df = pd.DataFrame({'A' : [1, 2, 3],
1176-
'B' : ['foo', 'bar', 'baz'],
1175+
>>> df = pd.DataFrame({'A' : [1, 1, 2],
1176+
'B' : ['foo', 'bar', 'foo'],
11771177
'C' : np.arange(4.,7)})
11781178
>>> df
11791179
A B C
11801180
0 1 foo 4.0
1181-
1 2 bar 5.0
1182-
2 3 baz 6.0
1181+
1 1 bar 5.0
1182+
2 2 foo 6.0
11831183
11841184
>>> df.to_xarray()
11851185
<xarray.Dataset>
11861186
Dimensions: (index: 3)
11871187
Coordinates:
11881188
* index (index) int64 0 1 2
11891189
Data variables:
1190-
A (index) int64 1 2 3
1191-
B (index) object 'foo' 'bar' 'baz'
1190+
A (index) int64 1 1 2
1191+
B (index) object 'foo' 'bar' 'foo'
11921192
C (index) float64 4.0 5.0 6.0
11931193
1194+
>>> df = pd.DataFrame({'A' : [1, 1, 2],
1195+
'B' : ['foo', 'bar', 'foo'],
1196+
'C' : np.arange(4.,7)}
1197+
).set_index(['B','A'])
1198+
>>> df
1199+
C
1200+
B A
1201+
foo 1 4.0
1202+
bar 1 5.0
1203+
foo 2 6.0
1204+
1205+
>>> df.to_xarray()
1206+
<xarray.Dataset>
1207+
Dimensions: (A: 2, B: 2)
1208+
Coordinates:
1209+
* B (B) object 'bar' 'foo'
1210+
* A (A) int64 1 2
1211+
Data variables:
1212+
C (B, A) float64 5.0 nan 4.0 6.0
1213+
11941214
>>> p = pd.Panel(np.arange(24).reshape(4,3,2),
11951215
items=list('ABCD'),
11961216
major_axis=pd.date_range('20130101', periods=3),

pandas/tests/test_generic.py

+18-2
Original file line numberDiff line numberDiff line change
@@ -1832,10 +1832,26 @@ def test_to_xarray(self):
18321832
expected,
18331833
check_index_type=False)
18341834

1835-
# not implemented
1835+
# available in 0.7.1
1836+
# MultiIndex
18361837
df.index = pd.MultiIndex.from_product([['a'], range(3)],
18371838
names=['one', 'two'])
1838-
self.assertRaises(ValueError, lambda: df.to_xarray())
1839+
result = df.to_xarray()
1840+
self.assertEqual(result.dims['one'], 1)
1841+
self.assertEqual(result.dims['two'], 3)
1842+
self.assertEqual(len(result.coords), 2)
1843+
self.assertEqual(len(result.data_vars), 8)
1844+
assert_almost_equal(list(result.coords.keys()), ['one', 'two'])
1845+
self.assertIsInstance(result, Dataset)
1846+
1847+
result = result.to_dataframe()
1848+
expected = df.copy()
1849+
expected['f'] = expected['f'].astype(object)
1850+
expected['h'] = expected['h'].astype('datetime64[ns]')
1851+
expected.columns.name = None
1852+
assert_frame_equal(result,
1853+
expected,
1854+
check_index_type=False)
18391855

18401856

18411857
class TestPanel(tm.TestCase, Generic):

0 commit comments

Comments
 (0)