Drawing solid line in pandas dataframe every time column value changes

Viewed 132

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

2 Answers

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

You can find the index of last row of a group using shift and boolean operations like so

Code:

df = pd.DataFrame({"product_basket":["CAT","CAT","CAT","CAT","FUR","FUR","FUR","FUR","HYG","HYG"]})

df['last_of_group'] = (df['product_basket'].shift() != df['product_basket']).shift(-1).fillna(False)

print(df)

Output:

  product_basket  last_of_group
0            CAT          False
1            CAT          False
2            CAT          False
3            CAT           True
4            FUR          False
5            FUR          False
6            FUR          False
7            FUR           True
8            HYG          False
9            HYG          False

Then you can do your formatting on those rows.

Related