Convert a dataframe of all float columns to a 2D xarray? #7526
-
(just started looking at xarray, sorry if I overlooked something). Is it possible to simply convert (a selection of columns) from a dataframe to a 2D DataArray and e.g. add the index or another column as the coordinate for the first dimension and the selected column names as the coordinates for the second dimension? This seems to be intuitively one of the most basic and straightforward conversions (e.g. for a DF that contains a multidimensional time series) but I have not seen it mentioned anywhere. I know I can use my own code to first create the 2d numpy array and the dataarray, but I was wondering if a utility function for this maybe exists? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Does this help: https://docs.xarray.dev/en/stable/generated/xarray.Dataset.from_dataframe.html There is an equivalent DataFrame.to_xarray that calls this function IIRC |
Beta Was this translation helpful? Give feedback.
-
You can simply pass a Dataframe to the DataArray constructor: import xarray as xr
import sklearn.datasets as skd
xdf, ydf = skd.load_iris(return_X_y=True, as_frame=True)
da = xr.DataArray(xdf) (note: this does drop the name of the index dimensions) Or you can convert the dataframe to a Dataset then to a DataArray: xdf.to_xarray().to_array() |
Beta Was this translation helpful? Give feedback.
You can simply pass a Dataframe to the DataArray constructor:
(note: this does drop the name of the index dimensions)
Or you can convert the dataframe to a Dataset then to a DataArray: