Prepare and wrap data to put in a Variable. - If data does not have the necessary attributes, convert it to ndarray. - If it's a pandas.Timestamp, convert it to datetime64. - If data is already a pandas or xarray object (other than an Index), just use the values. Finally, wra
(
data: T_DuckArray | np.typing.ArrayLike, fastpath: bool = False
)
| 243 | |
| 244 | |
| 245 | def as_compatible_data( |
| 246 | data: T_DuckArray | np.typing.ArrayLike, fastpath: bool = False |
| 247 | ) -> T_DuckArray: |
| 248 | """Prepare and wrap data to put in a Variable. |
| 249 | |
| 250 | - If data does not have the necessary attributes, convert it to ndarray. |
| 251 | - If it's a pandas.Timestamp, convert it to datetime64. |
| 252 | - If data is already a pandas or xarray object (other than an Index), just |
| 253 | use the values. |
| 254 | |
| 255 | Finally, wrap it up with an adapter if necessary. |
| 256 | """ |
| 257 | if fastpath and getattr(data, "ndim", None) is not None: |
| 258 | return cast("T_DuckArray", data) |
| 259 | |
| 260 | from xarray.core.dataarray import DataArray |
| 261 | |
| 262 | # TODO: do this uwrapping in the Variable/NamedArray constructor instead. |
| 263 | if isinstance(data, Variable): |
| 264 | return cast("T_DuckArray", data._data) |
| 265 | |
| 266 | # TODO: do this uwrapping in the DataArray constructor instead. |
| 267 | if isinstance(data, DataArray): |
| 268 | return cast("T_DuckArray", data._variable._data) |
| 269 | |
| 270 | def convert_non_numpy_type(data): |
| 271 | return cast("T_DuckArray", _maybe_wrap_data(data)) |
| 272 | |
| 273 | if isinstance(data, NON_NUMPY_SUPPORTED_ARRAY_TYPES): |
| 274 | return convert_non_numpy_type(data) |
| 275 | |
| 276 | if isinstance(data, tuple): |
| 277 | data = utils.to_0d_object_array(data) |
| 278 | |
| 279 | # we don't want nested self-described arrays |
| 280 | if isinstance(data, pd.Series | pd.DataFrame): |
| 281 | if ( |
| 282 | isinstance(data, pd.Series) |
| 283 | and is_allowed_extension_array(data.array) |
| 284 | # Some datetime types are not allowed as well as backing Variable types |
| 285 | and not isinstance(data.array, UNSUPPORTED_EXTENSION_ARRAY_TYPES) |
| 286 | ): |
| 287 | pandas_data = data.array |
| 288 | else: |
| 289 | pandas_data = data.values # type: ignore[assignment] |
| 290 | if isinstance(pandas_data, NON_NUMPY_SUPPORTED_ARRAY_TYPES): |
| 291 | return convert_non_numpy_type(pandas_data) |
| 292 | else: |
| 293 | data = pandas_data |
| 294 | |
| 295 | if isinstance(data, np.ma.MaskedArray) or ( |
| 296 | isinstance(data, array_type("dask")) |
| 297 | and isinstance(getattr(data, "_meta", None), np.ma.MaskedArray) |
| 298 | ): |
| 299 | mask = duck_array_ops.getmaskarray(data) |
| 300 | data = duck_array_ops.where_method(data, ~mask) |
| 301 | |
| 302 | if isinstance(data, np.matrix): |
searching dependent graphs…