Is there a simple way to convert an xarray DataArray to a pandas DataFrame, where I can prescribe which dimensions get turned into index/columns? For example, suppose I have a DataArray
import xarray as xr
weather = xr.DataArray(
name='weather',
data=[['Sunny', 'Windy'], ['Rainy', 'Foggy']],
dims=['date', 'time'],
coords={
'date': ['Thursday', 'Friday'],
'time': ['Morning', 'Afternoon'],
}
)
which results in:
<xarray.DataArray 'weather' (date: 2, time: 2)>
array([['Sunny', 'Windy'],
['Rainy', 'Foggy']], dtype='<U5')
Coordinates:
* date (date) <U8 'Thursday' 'Friday'
* time (time) <U9 'Morning' 'Afternoon'
Suppose I now want to move that to a pandas DataFrame indexed by date, with columns time. I can kind of do this by using .to_dataframe() and then .unstack() on the resulting dataframe:
>>> weather.to_dataframe().unstack()
weather
time Afternoon Morning
date
Friday Foggy Rainy
Thursday Windy Sunny
However, pandas will sort things so rather than Morning followed by Afternoon, I get Afternoon followed by Morning. I was rather hoping there would be an API like
weather.to_dataframe(index_dims=[...], column_dims=[...])
which could do this reshaping for me, without me having to re-sort my indices and columns afterwards.