Open LastsForever opened 4 years ago
Thanks for the report! It seems writing might have a related issue. Doing:
df = pd.DataFrame({'a': 3 * [None]}, index=[1, 2, 3])
df.columns = pd.MultiIndex.from_arrays([['A'], ['x']])
df.to_excel('test.xlsx')
produces an empty line below the columns. Reading this in produces the original DataFrame correctly. If I first delete this empty line and then read in the excel file, I get the issue mentioned above.
It looks like this behaviour was intentional. The reader interprets the blank spaces the same way the writer does, and "in the case of column MultiIndex a blank row ALWAYS has to be inserted so the format is unambiguous. I believe this is unavoidable (csv does it too) - but the output looks a little odd if the index doesn't have names." https://github.com/pandas-dev/pandas/pull/10967#issuecomment-137603832
Also, https://github.com/pandas-dev/pandas/pull/10967#issuecomment-137714842 points out this exact case as being ambiguous:
There's no way to know if "a" is the index name or if the data row is blank. Pandas assumes that "a" is the index name because that's how it writes named MulitIndex dataframes.
Thanks @ahawryluk. I don't see any options that would improve upon this, but perhaps a note in the documentation of read_excel may be useful.
[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.
[ ] (optional) I have confirmed this bug exists on the master branch of pandas.
Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.
There is a file a.xlsx with only index and multi-level columns:
pd.read_excel('a.xlsx', index_col=0, header=[0, 1])
creates a DataFrame with incorrect multi-level columns:However, if the file b.xlsx with the same structure (shown below) is not empty, the result appears to be correct:
Problem description
The parameter
header=[0, 1]
indicates that the first two rows of the excel file should be used as multi-level columns, but the result got first three rows as the multi-level columns.Expected Output
pd.read_excel('a.xlsx', index_col=0, header=[0, 1])
should get the DataFrame:Output of
pd.show_versions()