Skip to content

Commit 03d409e

Browse files
authored
Improve the speed of from_dataframe with a MultiIndex (by 40x!) (#4184)
* Add MultiIndexSeries.time_to_xarray() benchmark * Improve the speed of from_dataframe with a MultiIndex Fixes GH-2459 Before: pandas.MultiIndexSeries.time_to_xarray ======= ========= ========== -- subset ------- -------------------- dtype True False ======= ========= ========== int 505±0ms 37.1±0ms float 485±0ms 38.3±0ms ======= ========= ========== After: pandas.MultiIndexSeries.time_to_xarray ======= ========= ========== -- subset ------- -------------------- dtype True False ======= ========= ========== int 11.5±0ms 39.2±0ms float 12.5±0ms 26.6±0ms ======= ========= ========== There are still some cases where we have to fall back to the existing slow implementation, but hopefully they should now be relatively rare. * remove unused import * Simplify converting MultiIndex dataframes * remove comments * remove types with NA * more multiindex dataframe tests * add whats new note * Preserve order of MultiIndex levels in from_dataframe * Add todo note * Rewrite from_dataframe to avoid passing around a dataframe * Require that MultiIndexes are unique even with sparse=True * clarify comment
1 parent e216720 commit 03d409e

File tree

5 files changed

+127
-30
lines changed

5 files changed

+127
-30
lines changed

asv_bench/benchmarks/pandas.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import numpy as np
2+
import pandas as pd
3+
4+
from . import parameterized
5+
6+
7+
class MultiIndexSeries:
8+
def setup(self, dtype, subset):
9+
data = np.random.rand(100000).astype(dtype)
10+
index = pd.MultiIndex.from_product(
11+
[
12+
list("abcdefhijk"),
13+
list("abcdefhijk"),
14+
pd.date_range(start="2000-01-01", periods=1000, freq="B"),
15+
]
16+
)
17+
series = pd.Series(data, index)
18+
if subset:
19+
series = series[::3]
20+
self.series = series
21+
22+
@parameterized(["dtype", "subset"], ([int, float], [True, False]))
23+
def time_to_xarray(self, dtype, subset):
24+
self.series.to_xarray()

doc/whats-new.rst

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,10 @@ Enhancements
4949
For orthogonal linear- and nearest-neighbor interpolation, we do 1d-interpolation sequentially
5050
rather than interpolating in multidimensional space. (:issue:`2223`)
5151
By `Keisuke Fujii <https://github.com/fujiisoup>`_.
52-
- :py:meth:`DataArray.reset_index` and :py:meth:`Dataset.reset_index` now keep
52+
- Major performance improvement for :py:meth:`Dataset.from_dataframe` when the
53+
dataframe has a MultiIndex (:pull:`4184`).
54+
By `Stephan Hoyer <https://github.com/shoyer>`_.
55+
- :py:meth:`DataArray.reset_index` and :py:meth:`Dataset.reset_index` now keep
5356
coordinate attributes (:pull:`4103`). By `Oriol Abril <https://github.com/OriolAbril>`_.
5457

5558
New Features
@@ -133,8 +136,9 @@ Bug fixes
133136
By `Deepak Cherian <https://github.com/dcherian>`_.
134137
- ``ValueError`` is raised when ``fill_value`` is not a scalar in :py:meth:`full_like`. (:issue:`3977`)
135138
By `Huite Bootsma <https://github.com/huite>`_.
136-
- Fix wrong order in converting a ``pd.Series`` with a MultiIndex to ``DataArray``. (:issue:`3951`)
137-
By `Keisuke Fujii <https://github.com/fujiisoup>`_.
139+
- Fix wrong order in converting a ``pd.Series`` with a MultiIndex to ``DataArray``.
140+
(:issue:`3951`, :issue:`4186`)
141+
By `Keisuke Fujii <https://github.com/fujiisoup>`_ and `Stephan Hoyer <https://github.com/shoyer>`_.
138142
- Fix renaming of coords when one or more stacked coords is not in
139143
sorted order during stack+groupby+apply operations. (:issue:`3287`,
140144
:pull:`3906`) By `Spencer Hill <https://github.com/spencerahill>`_

xarray/core/dataset.py

Lines changed: 46 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4543,11 +4543,10 @@ def to_dataframe(self):
45434543
return self._to_dataframe(self.dims)
45444544

45454545
def _set_sparse_data_from_dataframe(
4546-
self, dataframe: pd.DataFrame, dims: tuple
4546+
self, idx: pd.Index, arrays: List[Tuple[Hashable, np.ndarray]], dims: tuple
45474547
) -> None:
45484548
from sparse import COO
45494549

4550-
idx = dataframe.index
45514550
if isinstance(idx, pd.MultiIndex):
45524551
coords = np.stack([np.asarray(code) for code in idx.codes], axis=0)
45534552
is_sorted = idx.is_lexsorted()
@@ -4557,11 +4556,7 @@ def _set_sparse_data_from_dataframe(
45574556
is_sorted = True
45584557
shape = (idx.size,)
45594558

4560-
for name, series in dataframe.items():
4561-
# Cast to a NumPy array first, in case the Series is a pandas
4562-
# Extension array (which doesn't have a valid NumPy dtype)
4563-
values = np.asarray(series)
4564-
4559+
for name, values in arrays:
45654560
# In virtually all real use cases, the sparse array will now have
45664561
# missing values and needs a fill_value. For consistency, don't
45674562
# special case the rare exceptions (e.g., dtype=int without a
@@ -4580,18 +4575,36 @@ def _set_sparse_data_from_dataframe(
45804575
self[name] = (dims, data)
45814576

45824577
def _set_numpy_data_from_dataframe(
4583-
self, dataframe: pd.DataFrame, dims: tuple
4578+
self, idx: pd.Index, arrays: List[Tuple[Hashable, np.ndarray]], dims: tuple
45844579
) -> None:
4585-
idx = dataframe.index
4586-
if isinstance(idx, pd.MultiIndex):
4587-
# expand the DataFrame to include the product of all levels
4588-
full_idx = pd.MultiIndex.from_product(idx.levels, names=idx.names)
4589-
dataframe = dataframe.reindex(full_idx)
4590-
shape = tuple(lev.size for lev in idx.levels)
4591-
else:
4592-
shape = (idx.size,)
4593-
for name, series in dataframe.items():
4594-
data = np.asarray(series).reshape(shape)
4580+
if not isinstance(idx, pd.MultiIndex):
4581+
for name, values in arrays:
4582+
self[name] = (dims, values)
4583+
return
4584+
4585+
shape = tuple(lev.size for lev in idx.levels)
4586+
indexer = tuple(idx.codes)
4587+
4588+
# We already verified that the MultiIndex has all unique values, so
4589+
# there are missing values if and only if the size of output arrays is
4590+
# larger that the index.
4591+
missing_values = np.prod(shape) > idx.shape[0]
4592+
4593+
for name, values in arrays:
4594+
# NumPy indexing is much faster than using DataFrame.reindex() to
4595+
# fill in missing values:
4596+
# https://stackoverflow.com/a/35049899/809705
4597+
if missing_values:
4598+
dtype, fill_value = dtypes.maybe_promote(values.dtype)
4599+
data = np.full(shape, fill_value, dtype)
4600+
else:
4601+
# If there are no missing values, keep the existing dtype
4602+
# instead of promoting to support NA, e.g., keep integer
4603+
# columns as integers.
4604+
# TODO: consider removing this special case, which doesn't
4605+
# exist for sparse=True.
4606+
data = np.zeros(shape, values.dtype)
4607+
data[indexer] = values
45954608
self[name] = (dims, data)
45964609

45974610
@classmethod
@@ -4631,7 +4644,19 @@ def from_dataframe(cls, dataframe: pd.DataFrame, sparse: bool = False) -> "Datas
46314644
if not dataframe.columns.is_unique:
46324645
raise ValueError("cannot convert DataFrame with non-unique columns")
46334646

4634-
idx, dataframe = remove_unused_levels_categories(dataframe.index, dataframe)
4647+
idx = remove_unused_levels_categories(dataframe.index)
4648+
4649+
if isinstance(idx, pd.MultiIndex) and not idx.is_unique:
4650+
raise ValueError(
4651+
"cannot convert a DataFrame with a non-unique MultiIndex into xarray"
4652+
)
4653+
4654+
# Cast to a NumPy array first, in case the Series is a pandas Extension
4655+
# array (which doesn't have a valid NumPy dtype)
4656+
# TODO: allow users to control how this casting happens, e.g., by
4657+
# forwarding arguments to pandas.Series.to_numpy?
4658+
arrays = [(k, np.asarray(v)) for k, v in dataframe.items()]
4659+
46354660
obj = cls()
46364661

46374662
if isinstance(idx, pd.MultiIndex):
@@ -4647,9 +4672,9 @@ def from_dataframe(cls, dataframe: pd.DataFrame, sparse: bool = False) -> "Datas
46474672
obj[index_name] = (dims, idx)
46484673

46494674
if sparse:
4650-
obj._set_sparse_data_from_dataframe(dataframe, dims)
4675+
obj._set_sparse_data_from_dataframe(idx, arrays, dims)
46514676
else:
4652-
obj._set_numpy_data_from_dataframe(dataframe, dims)
4677+
obj._set_numpy_data_from_dataframe(idx, arrays, dims)
46534678
return obj
46544679

46554680
def to_dask_dataframe(self, dim_order=None, set_index=False):

xarray/core/indexes.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from .variable import Variable
1010

1111

12-
def remove_unused_levels_categories(index, dataframe=None):
12+
def remove_unused_levels_categories(index: pd.Index) -> pd.Index:
1313
"""
1414
Remove unused levels from MultiIndex and unused categories from CategoricalIndex
1515
"""
@@ -25,14 +25,15 @@ def remove_unused_levels_categories(index, dataframe=None):
2525
else:
2626
level = level[index.codes[i]]
2727
levels.append(level)
28+
# TODO: calling from_array() reorders MultiIndex levels. It would
29+
# be best to avoid this, if possible, e.g., by using
30+
# MultiIndex.remove_unused_levels() (which does not reorder) on the
31+
# part of the MultiIndex that is not categorical, or by fixing this
32+
# upstream in pandas.
2833
index = pd.MultiIndex.from_arrays(levels, names=index.names)
2934
elif isinstance(index, pd.CategoricalIndex):
3035
index = index.remove_unused_categories()
31-
32-
if dataframe is None:
33-
return index
34-
dataframe = dataframe.set_index(index)
35-
return dataframe.index, dataframe
36+
return index
3637

3738

3839
class Indexes(collections.abc.Mapping):

xarray/tests/test_dataset.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4013,6 +4013,49 @@ def test_to_and_from_empty_dataframe(self):
40134013
assert len(actual) == 0
40144014
assert expected.equals(actual)
40154015

4016+
def test_from_dataframe_multiindex(self):
4017+
index = pd.MultiIndex.from_product([["a", "b"], [1, 2, 3]], names=["x", "y"])
4018+
df = pd.DataFrame({"z": np.arange(6)}, index=index)
4019+
4020+
expected = Dataset(
4021+
{"z": (("x", "y"), [[0, 1, 2], [3, 4, 5]])},
4022+
coords={"x": ["a", "b"], "y": [1, 2, 3]},
4023+
)
4024+
actual = Dataset.from_dataframe(df)
4025+
assert_identical(actual, expected)
4026+
4027+
df2 = df.iloc[[3, 2, 1, 0, 4, 5], :]
4028+
actual = Dataset.from_dataframe(df2)
4029+
assert_identical(actual, expected)
4030+
4031+
df3 = df.iloc[:4, :]
4032+
expected3 = Dataset(
4033+
{"z": (("x", "y"), [[0, 1, 2], [3, np.nan, np.nan]])},
4034+
coords={"x": ["a", "b"], "y": [1, 2, 3]},
4035+
)
4036+
actual = Dataset.from_dataframe(df3)
4037+
assert_identical(actual, expected3)
4038+
4039+
df_nonunique = df.iloc[[0, 0], :]
4040+
with raises_regex(ValueError, "non-unique MultiIndex"):
4041+
Dataset.from_dataframe(df_nonunique)
4042+
4043+
def test_from_dataframe_unsorted_levels(self):
4044+
# regression test for GH-4186
4045+
index = pd.MultiIndex(
4046+
levels=[["b", "a"], ["foo"]], codes=[[0, 1], [0, 0]], names=["lev1", "lev2"]
4047+
)
4048+
df = pd.DataFrame({"c1": [0, 2], "c2": [1, 3]}, index=index)
4049+
expected = Dataset(
4050+
{
4051+
"c1": (("lev1", "lev2"), [[0], [2]]),
4052+
"c2": (("lev1", "lev2"), [[1], [3]]),
4053+
},
4054+
coords={"lev1": ["b", "a"], "lev2": ["foo"]},
4055+
)
4056+
actual = Dataset.from_dataframe(df)
4057+
assert_identical(actual, expected)
4058+
40164059
def test_from_dataframe_non_unique_columns(self):
40174060
# regression test for GH449
40184061
df = pd.DataFrame(np.zeros((2, 2)))

0 commit comments

Comments
 (0)