def from_dataframe(cls, dataframe: pd.DataFrame, sparse: bool = False) -> Self:
        """Convert a pandas.DataFrame into an xarray.Dataset

        Each column will be converted into an independent variable in the
        Dataset. If the dataframe's index is a MultiIndex, it will be expanded
        into a tensor product of one-dimensional indices (filling in missing
        values with NaN). If you rather preserve the MultiIndex use
        `xr.Dataset(df)`. This method will produce a Dataset very similar to
        that on which the 'to_dataframe' method was called, except with
        possibly redundant dimensions (since all dataset variables will have
        the same dimensionality).

        Parameters
        ----------
        dataframe : DataFrame
            DataFrame from which to copy data and indices.
        sparse : bool, default: False
            If true, create a sparse arrays instead of dense numpy arrays. This
            can potentially save a large amount of memory if the DataFrame has
            a MultiIndex. Requires the sparse package (sparse.pydata.org).

        Returns
        -------
        New Dataset.

        See Also
        --------
        xarray.DataArray.from_series
        pandas.DataFrame.to_xarray
        """
        # TODO: Add an option to remove dimensions along which the variables
        # are constant, to enable consistent serialization to/from a dataframe,
        # even if some variables have different dimensionality.

        if not dataframe.columns.is_unique:
            raise ValueError("cannot convert DataFrame with non-unique columns")

        idx = remove_unused_levels_categories(dataframe.index)

        if isinstance(idx, pd.MultiIndex) and not idx.is_unique:
            raise ValueError(
                "cannot convert a DataFrame with a non-unique MultiIndex into xarray"
            )

        arrays = []
        extension_arrays = []
        for k, v in dataframe.items():
            if not is_extension_array_dtype(v) or isinstance(
                v.array, UNSUPPORTED_EXTENSION_ARRAY_TYPES
            ):
                arrays.append((k, np.asarray(v)))
            else:
                extension_arrays.append((k, v))

        indexes: dict[Hashable, Index] = {}
        index_vars: dict[Hashable, Variable] = {}

        if isinstance(idx, pd.MultiIndex):
            dims = tuple(
                name if name is not None else f"level_{n}"  # type: ignore[redundant-expr]
                for n, name in enumerate(idx.names)
            )
            for dim, lev in zip(dims, idx.levels, strict=True):
                xr_idx = PandasIndex(lev, dim)
                indexes[dim] = xr_idx
                index_vars.update(xr_idx.create_variables())
            arrays += [(k, np.asarray(v)) for k, v in extension_arrays]
            extension_arrays = []
        else:
            index_name = idx.name if idx.name is not None else "index"
            dims = (index_name,)
            xr_idx = PandasIndex(idx, index_name)
            indexes[index_name] = xr_idx
            index_vars.update(xr_idx.create_variables())

        obj = cls._construct_direct(index_vars, set(index_vars), indexes=indexes)

        if sparse:
            obj._set_sparse_data_from_dataframe(idx, arrays, dims)
        else:
            obj._set_numpy_data_from_dataframe(idx, arrays, dims)
        for name, extension_array in extension_arrays:
            obj[name] = (dims, extension_array)
        return obj[dataframe.columns] if len(dataframe.columns) else obj
Convert a pandas.DataFrame into an xarray.Dataset

        Each column will be converted into an independent variable in the
        Dataset. If the dataframe's index is a MultiIndex, it will be expanded
        into a tensor product of one-dimensional indices (filling in missing
        values with NaN). If you rather preserve the MultiIndex use
        `xr.Dataset(df)`. This method will produce a Dataset very similar to
        that on which the 'to_dataframe' method was called, except with
        possibly redundant dimensions (since all dataset variables will have
        the same dimensionality).

        Parameters
        ----------
        dataframe : DataFrame
            DataFrame from which to copy data and indices.
        sparse : bool, default: False
            If true, create a sparse arrays instead of dense numpy arrays. This
            can potentially save a large amount of memory if the DataFrame has
            a MultiIndex. Requires the sparse package (sparse.pydata.org).

        Returns
        -------
        New Dataset.

        See Also
        --------
        xarray.DataArray.from_series
        pandas.DataFrame.to_xarray
        
xarray/core/dataset.py