Pandas FutureWarning when using dataframe_to_rows on MultiIndex df
Created originally on Bitbucket by mkupfer (Maxim Kupfer)
I’m getting the following FutureWarning message when passing a MultiIndex dataframe through dataframe_to_rows:
openpyxl/utils/dataframe.py:35: FutureWarning: .labels was deprecated in version 0.24.0. Use .codes instead.
rows = expand_levels(df.columns.levels, df.columns.labels)
More info about this deprecation can be found here: https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.24.0.html#deprecations
While the code still runs and works fine the fix is actually quite simple, you just need to change the second parameter so that it becomes expand_levels(df.columns.levels, df.columns.codes)
This seems pretty trivial, but I’d be happy to submit a patch if you like.
Creating mock examples with pandas feels a bit contrived, but the below code will reproduce the warning:
import itertools
import pandas as pd
import numpy as np
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
index = pd.MultiIndex.from_tuples(
[i for i in itertools.product(['A', 'B'], ['One', 'Two', 'Three'])])
df = pd.DataFrame(np.random.randn(6,4), index=index)
wb = Workbook()
ws = wb.active
rows = dataframe_to_rows(df.T)
for row in rows:
ws.append(row)
Coincidentally, by building this example I also uncovered that this raised a bug that was previously marked as resolved https://bitbucket.org/openpyxl/openpyxl/issues/917/regression-in-cell-formatting-between. I will comment on that issue as well, but thought I would still mention here to connect the dots.