MCPcopy Index your code
hub / github.com/pydata/xarray / to_pandas

Method to_pandas

xarray/core/dataarray.py:3918–3959  ·  view source on GitHub ↗

Convert this array into a pandas object with the same shape. The type of the returned object depends on the number of DataArray dimensions: * 0D -> `xarray.DataArray` * 1D -> `pandas.Series` * 2D -> `pandas.DataFrame` Only works for arrays with 2 or

(self)

Source from the content-addressed store, hash-verified

3916 return self._replace_maybe_drop_dims(var)
3917
3918 def to_pandas(self) -> Self | pd.Series | pd.DataFrame:
3919 """Convert this array into a pandas object with the same shape.
3920
3921 The type of the returned object depends on the number of DataArray
3922 dimensions:
3923
3924 * 0D -> `xarray.DataArray`
3925 * 1D -> `pandas.Series`
3926 * 2D -> `pandas.DataFrame`
3927
3928 Only works for arrays with 2 or fewer dimensions.
3929
3930 The DataArray constructor performs the inverse transformation.
3931
3932 Returns
3933 -------
3934 result : DataArray | Series | DataFrame
3935 DataArray, pandas Series or pandas DataFrame.
3936 """
3937 # TODO: consolidate the info about pandas constructors and the
3938 # attributes that correspond to their indexes into a separate module?
3939 constructors: dict[int, Callable] = {
3940 0: lambda x: x,
3941 1: pd.Series,
3942 2: pd.DataFrame,
3943 }
3944 try:
3945 constructor = constructors[self.ndim]
3946 except KeyError as err:
3947 raise ValueError(
3948 f"Cannot convert arrays with {self.ndim} dimensions into "
3949 "pandas objects. Requires 2 or fewer dimensions."
3950 ) from err
3951 indexes = [self.get_index(dim) for dim in self.dims]
3952 if isinstance(self._variable._data, PandasExtensionArray):
3953 values = self._variable._data.array
3954 else:
3955 values = self.values
3956 pandas_object = constructor(values, *indexes)
3957 if isinstance(pandas_object, pd.Series):
3958 pandas_object.name = self.name
3959 return pandas_object
3960
3961 def to_dataframe(
3962 self, name: Hashable | None = None, dim_order: Sequence[Hashable] | None = None

Callers 6

test_roundtrip_dataarrayFunction · 0.95
test_to_pandasMethod · 0.95
test_shiftMethod · 0.95

Calls 1

get_indexMethod · 0.80

Tested by 6

test_roundtrip_dataarrayFunction · 0.76
test_to_pandasMethod · 0.76
test_shiftMethod · 0.76