I have a numpy array-like (as stated here, simply an object that can be used to create a numpy array), and want to create a pandas.Series from it. According to its documentation, it supports array-likes.
Now consider the following MWE.
import numpy as np
import pandas as pd
class ArrayLike:
def __array__(self, dtype = None):
return np.asarray([0, 1])
a = ArrayLike()
print(pd.Series(a))
print(pd.Series(np.asarray(a)))
This results in
0 <__main__.ArrayLike object at [...]>
dtype: object
0 0
1 1
dtype: int64
This is not what I would expect, since the whole point of the array-like is the ability to convert to a numpy array, so the behaviour when creating the series directly from my ArrayLike seems weird to me.
Is this intentional from pandas, and if so, what is the reasoning behind it? And is there any possibility to achive the behaviour of the second statement when directly calling pd.Series on my object?
__array__method is a relatively recent addition tonumpy, Even in your linked SO, the original 2016 answers don't mention it, and newer ones talk it about in the context oftyping. A Series does have an__array__method (used bynp.asarray(aSeries). But theSeries.__init__is much more complex, creating or using aindexas well as thedata. Looking for the__array__` method doesn't have same priority as withnp.asarray.Seriesdocs do not definearray likein the same way asnp.array. There's no mention of the__array__method.