Search code examples
pythonpandasdataframestyles

Drawing solid line in pandas dataframe every time column value changes


I'd like to draw a solid line in my pandas dataframe everytime a value in column "product_basket" resets.

This is how my df looks like:

enter image description here

What I'd like it to be is:

enter image description here

Pls feel free to suggest also other ideas in order to achieve a similar result.

Thanks in advance,

Stefano


Solution

  • You can first get the indices where the product_basket isn't the same as the next one, and apply border-bottom CSS styling for the rows whose indices match them:

    # `different` is a boolean series, we get the indices where it is True
    different = df.product_basket.ne(df.product_basket.shift(-1))
    inds = different[different].index
    
    # for each row, `row.name` gives the index and if the condition is OK,
    # we return a styling for the entire row with `len(row)`; else None
    df.style.apply(lambda row: ["border-bottom: 2px solid blue;"]*len(row)
                               if row.name in inds
                               else [""]*len(row), axis=1)
    

    With some sample data

    enter image description here