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

Improve to_dask_dataframe performance #7844

Merged
merged 5 commits into from
May 25, 2023
Merged
Changes from 1 commit
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
16 changes: 14 additions & 2 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -6403,7 +6403,14 @@ def to_dask_dataframe(
columns.extend(k for k in self.coords if k not in self.dims)
columns.extend(self.data_vars)

has_many_dims = len(ordered_dims) > 1
if has_many_dims:
ds_chunks = self.chunks
else:
ds_chunks = {}

series_list = []
df_meta = pd.DataFrame()
for name in columns:
try:
var = self.variables[name]
Expand All @@ -6422,8 +6429,13 @@ def to_dask_dataframe(
if not is_duck_dask_array(var._data):
var = var.chunk()

dask_array = var.set_dims(ordered_dims).chunk(self.chunks).data
series = dd.from_array(dask_array.reshape(-1), columns=[name])
if has_many_dims:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this really that impactful, can we optimize set_dims instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll think I'll save the has_many_dims paths for a future PR. I think it might introduce bugs if we don't consistently chunk with the same shape.

# Broadcast then flatten the array:
var_new_dims = var.set_dims(ordered_dims).chunk(ds_chunks)
dask_array = var_new_dims._data.reshape(-1)
else:
dask_array = var._data
series = dd.from_dask_array(dask_array, columns=name, meta=df_meta)
series_list.append(series)

df = dd.concat(series_list, axis=1)
Expand Down