Open dmparker0 opened 5 years ago
For your expected output you want None
in the index instead of NaN
right? I think reasonable so if you want to investigate and submit a patch would certainly be welcome
For your expected output you want None in the index instead of NaN right?
I would never expect None to appear in a DataFrame, since my understanding is that NaN (or NaT) is used universally for missing values. The issue isn't having NaN instead of None in the index, it's having NaN instead of the appropriate string values in the other columns.
FWIW, what seems to be happening is that None
is getting converted to np.nan
when the MultiIndex
is built, but the actual data are still labeled internally with None
. Then we try to "look up" the data here: https://github.com/pandas-dev/pandas/blob/master/pandas/core/internals/construction.py#L310, but
the keys aren't found in the index so we end up with np.nan
for values. Note that this doesn't happen if you change None
to np.nan
in your example, or if you use single values instead of tuples as your keys.
I wonder if the Index
constructor should be consistent in how it handles None
? It seems like it doesn't convert to np.nan
if you pass a list of scalars, but it does if you pass a list of tuples.
Confirmed to still occur in pandas 2.2.3. Also, if you replace None
with nan
it still won't work!
To anyone reading this, the workaround is to change
df = pd.DataFrame.from_dict(d, orient="index")
To
df = pd.DataFrame.from_records(list(d.values()))
df.index = pd.MultiIndex.from_tuples(d.keys())
Code Sample
Output
Problem description
When constructing a DataFrame from a dictionary with tuple keys, values for all columns are set to NaN if the index tuple contains None.
I only started encountering this bug when I upgraded from pandas 0.22 to pandas 0.25.
Possibly related: #19993
Expected Output
Output of
pd.show_versions()