0

When saving a df that has been style into excel, compiler return

KeyError: "['A'] not in index"

import pandas as pd
import numpy as np


def color_negative_red(value):
  if value < 0:
    color = 'red'
  elif value > 0:
    color = 'green'
  else:
    color = 'black'

  return 'color: %s' % color

np.random.seed(0)
arrays = [np.hstack([['One']*2, ['Two']*2]) , ['A', 'B', 'A', 'B']]
columns = pd.MultiIndex.from_arrays(arrays)
df=  pd.DataFrame(np.random.randn(5, 4), columns=list('ABCD'))
df.columns = columns
data=df.style.applymap(color_negative_red, subset=['A'])

data.to_excel('test.xlsx')

Expected output

enter image description here

P.S.: Similar post has been submitted to pandas git: https://github.com/pandas-dev/pandas/issues/42906 for a potential bug

2 Answers 2

1

This is nothing to do with Styler.to_excel. It is to do with the fact you are using a MultiIndex columns and not supplying a subset in a valid format.

As advised in the docs you must supply a valid .loc indexer.

The solution is to use:

df.style.applymap(color_negative_red, subset=(slice(None), (slice(None), 'A')))

or pandas Indexer if you prefer (these solutions are isomorphic)

ix = pd.IndexSlice
df.style.applymap(color_negative_red, subset=ix[:, ix[:, 'A']])

Note your output will affect only the text color because you have not used the background-color CSS attribute.

Sign up to request clarification or add additional context in comments.

Comments

0

Can you try that:

df.style.applymap(color_negative_red, subset=([slice(None), "A"]))

1 Comment

Thanks for dropping by @Coralien. Compiler throw :NotImplementedError: Index._join_level on non-unique index is not implemented when implementing you suggestion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.