2

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?

1 Answer 1

3

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])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the explanation. Does matplotlib.pyplot work in the similar way to support say plt.contour(tmp) ?
Yes, matplotlib calls np.array or a similar function such as np.asarray under the hood. This is considered a best practice for libraries that accept numpy arrays in function arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.