Skip to content

DataFrame with MultiIndex -> xarray with sparse array #3206

Closed
@shoyer

Description

@shoyer

Now that we have preliminary support for sparse arrays in xarray, one really cool feature we could explore is creating sparse arrays from MultiIndexed pandas DataFrames.

Right now, xarray's methods for creating objects from pandas always create dense arrays, but the size of these dense arrays can get big really quickly if the MultiIndex is sparsely populated, e.g.,

import pandas as pd
import numpy as np
import xarray
df = pd.DataFrame({
    'w': range(10),
    'x': list('abcdefghij'),
    'y': np.arange(0, 100, 10),
    'z': np.ones(10),
}).set_index(['w', 'x', 'y'])
print(xarray.Dataset.from_dataframe(df))

This length 10 DataFrame turned into a dense array with 1000 elements (only 10 of which are not NaN):

<xarray.Dataset>
Dimensions:  (w: 10, x: 10, y: 10)
Coordinates:
  * w        (w) int64 0 1 2 3 4 5 6 7 8 9
  * x        (x) object 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j'
  * y        (y) int64 0 10 20 30 40 50 60 70 80 90
Data variables:
    z        (w, x, y) float64 1.0 nan nan nan nan nan ... nan nan nan nan 1.0

We can imagine xarray.Dataset.from_dataframe(df, sparse=True) would make the same Dataset, but with sparse array (with a NaN fill value) instead of dense arrays.

Once sparse arrays work pretty well, this could actually obviate most of the use cases for MultiIndex in arrays. Arguably the model is quite a bit cleaner.

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic-arraysrelated to flexible array support

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions