1

Is there a fast method for this? I'm not quite getting that from the docs.

i.e. how to convert this to 3d xarray object with all the labels?

d = {x: pd.DataFrame(np.random.randn(4, 3)) for x in [1,2,3]}

def dict_of_df_to_xarray(d, key_name=None):
    import xarray
    keys = list(sorted(d.keys()))
    df = d[keys[0]]
    ind = df.index
    if key_name is None:
        key_name = 'key'
    columns = df.columns
    index_name = df.index.name
    if index_name is None:
        index_name = 'index'
    column_name = df.columns.name
    if column_name is None:
        column_name = 'column'
    df = xarray.DataArray(np.concatenate([d[k].values[:, :, None] for k in keys], axis=2), dims=[index_name, column_name,
        key_name], coords={index_name: ind, column_name: columns, key_name: keys})
    return df

6
  • could you show an expample? Commented Apr 24, 2020 at 17:54
  • Yep, posted an example. Commented Apr 24, 2020 at 17:59
  • Something like d2 = pd.concat([v for v in d.values()]).to_xarray() maybe. Commented Apr 24, 2020 at 18:06
  • Yeah, I just posted the long way. The question is whether there is that method in xarray somewhere. There should be really. Commented Apr 24, 2020 at 18:07
  • 1
    xr.Dataset(d).to_array()? Commented Apr 25, 2020 at 18:52

1 Answer 1

2

This is easier than it seems! Maybe we should add this to the docs...

xr.Dataset(d).to_array()
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, it's one of those things that easy once you know. It does feel like a common path (dict of dataframes to xarray).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.