For example I want to be able to highlight the first 17 rows in green in a dataframe. I've seen answers on how to highlight rows based on column value but nothing as simple as rows regardless of the value in a column. I don't care about the value in the rows.
TLDR: I just simply want to be able to color the first 17 rows green in a dataframe.
Thank you for your help!
df.style.applymap(lambda _: "background-color: green", subset=(df.index[:17],))
where we subset the styling area with a tuple to say we select rows (if tuple is stripped off, it interprets them as column names). Noting that we cannot directly write range(17)
there as not all dataframes have the default RangeIndex (0, 1 ...). Since we don't really care about the value residing in cells but the row index itself, _
is used in the coloring function to convey ignoring that.
Generalization for the first N rows:
# Color first N rows
N, color = 17, "lightgray"
df.style.applymap(lambda _: f"background-color: {color}", subset=(df.index[:N],))
Generalization for specific rows:
# Color specific rows
rows_to_color = [0, 4, 5, 12]
color = "lightgray"
df.style.applymap(lambda _: f"background-color: {color}",
subset=(df.index[rows_to_color],))