Open mesvam opened 2 months ago
Thanks for the report. I agree that this is unintuitive, but that is unfortunately because UserDict
is not a subclass of dict
. Because of this it appears to me that pandas is behaving in the way it is documented: cd
is not a dict, so pandas treats it as the iterable that it is creating a single-column DataFrame. So I've reworked this issue as a feature request.
I'm supportive of treating UserDict
as a dict as proposed here.
As a workaround, you can always pass cd.data
instead.
Thanks.
I searched around and found a similar issue here https://github.com/pandas-dev/pandas/issues/34257, so I don't know if they're related and it's a more general issue with pandas or just pandas.DataFrame.from_dict
specifically
Also, I can kind of understand if pd.DataFrame(dict_like)
didn't work, but pd.DataFrame.from_dict(dict_like)
feels like it should work with anything that inherits from collections.abc.Mapping
Also, I can kind of understand if
pd.DataFrame(dict_like)
didn't work...
Why is that?
but
pd.DataFrame.from_dict(dict_like)
feels like it should work with anything that inherits fromcollections.abc.Mapping
Thanks - I did initially miss that the OP was about from_dict
and not the constructor. Agreed here as well.
Also, I can kind of understand if
pd.DataFrame(dict_like)
didn't work...Why is that?
I think it would be ideal if it worked with pd.DataFrame
as well as pd.DataFrame.from_dict
, but my intuition was that since pd.DataFrame
takes in a variety of formats, I sort of assumed it would be easier to for it to get confused by a non-standard input type. Like I could probably create an weird class that can be accessed both like an array and as a dict, and I wouldn't really expect pd.DataFrame
to be able to correctly guess how I want it to access the object.
Whereas from_dict
should sort of implicitly assume that the input is a dict-like object and parse it as such, even if it's not the exact type it was expecting.
Could I take a go at this?
Pandas version checks
[X] I have checked that this issue has not already been reported.
[X] I have confirmed this bug exists on the latest version of pandas.
[ ] I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
output:
Issue Description
Pandas will not accept UserDict and other custom dict-like objects for DataFrame creation. Subclassing dict instead of UserDict is a workaround for this example, but for a variety of complicated reasons (examples: 1, 2, 3) it is sometimes undesirable to subclass dict.
Expected Behavior
The output should be the same as
output
Installed Versions