0

I have a pandas dataframe with MultiIndex. The indexes of the rows are 'time' and 'type' while the columns are built from tuples. The dataframe stores the information about the price and size of three cryptocurrencies pairs (either info about trades or about the best_bids). The details are not really important, but the dataframe looks like this

enter image description here

I would like to change the color of the rows for which 'type' == 'Buy Trade' (let's say I want to make the text of these rows green, and red otherwise).

How can I do it?

You can download the csv of the dataframe from here https://github.com/doogersPy/files/blob/main/dataframe.csv and then load the dataframe with

df = pd.read_csv('dataframe.csv',index_col=[0,1], header=[0,1])

I have tried a similar method presented in this other question, but df.style.applydoes not work with non-unique multindexes (like in my case). In my dataframe, there are entries with same time value.

In fact, I have tried the following code

def highlight(ob):
    c1 = f"background-color: #008000;" 
    c2 = f"background-color: #ff0000;" 
    
    m = ob.index.get_level_values('type') == 'Buy Trade'
    # DataFrame of styles
    df1 = pd.DataFrame('', index=ob.index, columns=ob.columns)
    # set columns by condition
    df1.loc[m, :] = c1
    df1.loc[~m, :] = c2

    #for check DataFrame of styles
    return df1

df.style.apply(highlight,axis=None)

but I get the error

KeyError: 'Styler.apply and .applymap are not compatible with non-unique index or columns.'

apt45
  • 412
  • 1
  • 6
  • 14

1 Answers1

0

I have solved with the following method

col=df.reset_index().columns
idx= df.reset_index().index

def highlight(ob):
    c_g = f"color: #008000;"  # Green
    c_r = f"color: #ff0000;"  # Red
    c_b = f"color: #000000;" #black
    mBuy = (ob['type'] == 'Buy Trade')
    mSell = (ob['type'] == 'Sell Trade')
    mOB = (ob['type'] == 'OB Update')
    # DataFrame of styles
    df1 = pd.DataFrame('', index=idx, columns=col)
    # set columns by condition
    df1.loc[mBuy] = c_g
    df1.loc[mSell] = c_r
    df1.loc[mOB] = c_b

    #for check DataFrame of styles
    return df1

df.reset_index().style.apply(highlight,axis=None)
apt45
  • 412
  • 1
  • 6
  • 14