Reputation: 309
To put the question in the simplest way -- how does the last line of this code work?
import numpy as np
import xarray as xr
tmp = xr.DataArray(np.random.rand(100,100))
howthiswork = np.array(tmp)
I'm under the impression that pandas is built on the top numpy link and then xarray is sort of based on pandas link. However, I don't find any info stating that numpy itself supports xarray.DataArray, plus not a lot of people are using xarray than numpy. So why can I initialize a numpy.ndarray with an xarray.DataArray object? One of my guess is that corresponding supporting is provided in the xarray package but I don't see a mechanism where codes from xarray package could affect numpy.ndarray.__init__ (or whatever function from numpy package)..
Can anyone give me an explanation of how this up-down support is achieved?
Upvotes: 2
Views: 153
Reputation: 9603
NumPy's looks for a __array__
method for how to convert arbitrary objects to numpy array, which both pandas and xarray objects define.
This is pretty easy to implement for your own class, e.g.,
import numpy as np
class MyArray:
def __array__(self, dtype=None):
return np.arange(5)
np.array(MyArray())
# array([0, 1, 2, 3, 4])
Upvotes: 3