Search code examples
pythonpandasdataframeexport-to-excelpandas-styles

Formating numbers in multiindex array Pandas


I have a dataframe that looks like this:

    Admin  ...  Unnamed: 14
Job Family Name                    Values                     ...             
Dentist    McDentistFace, Dentist  UDS Encounters   0.000000  ...     1.000000
                                   Actual FTE       0.000000  ...     1.000000
                                   UDS Encounters2       NaN  ...  1475.000000
                                   Actual FTE2           NaN  ...     7.589426

Where the Job Family, Name, and Values are all dimensions of a multiindex.

I'm trying to format the float values in the file, but can't seem to get it to work. I have been able to highlight certain rows with this line:

for i in flagged_providers:
ind = flagged_providers.index(i) * 4
for q in i.results.keys():
    style.apply(highlight_col, axis=0, subset=(style.index[ind: ind + 4], q))
    # style.apply(format_numbers, axis=0, subset=(style.index[ind: ind + 2], q))

where format_numbers is:

def format_numbers(s):
return f'{s:,.2f}'

and I have also tried this:

for i in flagged_providers:
    format_dict[(i.jfam, i.name)] = '{:.2f}'
    format_dict[(i.jfam, i.name)] = '{:.2f}'
style.format(formatter=format_dict)

But I can't quite seem to get it to work. Hoping for any ideas? I want to format the first two rows as percentages, then export to excel using the to_excel function.


Solution

  • I figured it out finally. Probably a better way to do this but what worked was:

    style.applymap(lambda x: 'number-format:0.00%;', subset=(style.index[ind: ind + 2], locations))