I have a multiindex dataframe, I provided minimal reproducable sample.
import pandas as pd
import numpy as np
import string
index = pd.MultiIndex.from_product(
([2020], [1, 2, 3, 4]), names=['year', 'q']
)
columns = pd.MultiIndex.from_product(
(['Items1', 'Items2', 'Items3'], ['new', 'old']),
names=['Items', 'type']
)
data = np.random.seed(123)
data = list(np.random.choice(list(string.ascii_lowercase), (4,6)))
Ldata = pd.DataFrame(data, index=index, columns=columns)
Ldata
And I want to mark certain values in dataframe, and I'm doing it like this. But I don't know where to put multiindex level=1
. I tried but I got errors, where I can add level?
def highlight_cells(x):
c = 'background-color: white'
c1 = 'background-color: red'
c2 = 'background-color: blue'
c3 = 'background-color: green'
k1 = Ldata['new'].str.contains("a", na=False)
k2 = Ldata['new'].str.contains("b", na=False)
k3 = Ldata['new'].str.contains("c", na=False)
colordata = pd.DataFrame(c, index=x.index, columns=x.columns)
colordata.loc[k1, 'new'] = c1
colordata.loc[k2, 'new'] = c2
colordata.loc[k3, 'new'] = c3
return colordata
end = Ldata.style.apply(highlight_cells,axis=None)
end
Thanks in advance!
CodePudding user response:
Maybe the easiest way is to stack the DataFrame like this before applying the function:
Ldata = Ldata.stack('Items')
Then you can leave the rest of your code as it is.
CodePudding user response:
It seems like you are trying to modify every "new"
column, across levels of "Items"
columns.