Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow data instantiation from a xarray.DataArray object #711

Merged
merged 1 commit into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ version 3.17.0

**2024-??-??**

* Allow `cf.Data` to be initialised with `xarray.DataAarray`
(https://github.com/NCAS-CMS/cf-python/issues/706)
* Fix bug that caused `cf.Field.del_file_location` to fail when
updating its metdata constructs
(https://github.com/NCAS-CMS/cf-python/issues/707)
Expand Down
10 changes: 8 additions & 2 deletions cf/data/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ def to_dask(array, chunks, **from_array_options):

array: array_like
The array to be converted to a `dask` array. Examples of
valid types include `numpy` arrays, `dask` arrays, `Array`
subclasses, `list`, `tuple`, scalars.
valid types include anything with a `to_dask_array`
method, `numpy` arrays, `dask` arrays, `xarray` arrays,
`cf.Array` subclasses, `list`, `tuple`, scalars.

chunks: `int`, `tuple`, `dict` or `str`, optional
Specify the chunking of the returned dask array. Any
Expand Down Expand Up @@ -68,6 +69,11 @@ def to_dask(array, chunks, **from_array_options):
except TypeError:
return array.to_dask_array()

if type(array).__module__.split(".")[0] == "xarray":
data = getattr(array, "data", None)
if data is not None:
return da.asanyarray(data)

if not isinstance(
array, (np.ndarray, list, tuple, memoryview) + np.ScalarType
) and not hasattr(array, "shape"):
Expand Down
9 changes: 6 additions & 3 deletions cf/data/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,11 +189,14 @@ def __init__(
:Parameters:

array: optional
The array of values. May be any scalar or array-like
object, including another `Data` instance.
The array of values. May be a scalar or array-like
object, including another `Data` instance, anything
with a `!to_dask_array` method, `numpy` array, `dask`
array, `xarray` array, `cf.Array` subclass, `list`,
`tuple`, scalar.

*Parameter example:*
``array=[34.6]``
``array=34.6``

*Parameter example:*
``array=[[1, 2], [3, 4]]``
Expand Down
Loading