highlight (color) a panda data frame row by index
Asked Answered
B

2

7

i have two data frame df1:

d1 = {"col1" : ['A', 'B', 'C'],
      "Col2": ["home", "car","banana" ]}

d2 = {"col1" : ['D', 'F','C'],
      "Col2": ["garden", "boat","banana" ]}

df1 = pd.DataFrame(data=d1)
df2 = pd.DataFrame(data=d2)

new_df = pd.merge(df1, df2,  on ='col1', how='outer')
new_df

So what I am trying to do is highlight the third row "banana" that was found in the two data frames. I was using the Styling documentation to find a solution but no luck. I was able to highlight only a single row, but when I have multiple rows it doesn't work. Please give a helping hand

Biplane answered 30/4, 2018 at 12:32 Comment(0)
O
7

In case you want to highlight two rows (say index 2 and 4) it is a almost a duplicate of this answer

new_df.style.apply(lambda x: ['background: lightgreen' if x.name in [2,4] 
                              else '' for i in x], 
                   axis=1)

If instead you are looking to highlight every row that contain a given name in a list (i.e. lst = ['car', 'boat']) you can use

new_df.style.apply(lambda x: ['background: lightgreen' if (set(lst).intersection(x.values)) 
                              else '' for i in x], 
                   axis=1)
Overseas answered 30/4, 2018 at 13:7 Comment(2)
Thank you that, it did the trick. but how can i keep the coloring if i want to add another color in the dataframe?Biplane
@ilatikkral if you want to add more colors you could use an if, elif, else statement in your list of comprehension.Overseas
P
2

Lots of questions link here regarding styling a DataFrame row, so I kept coming here despite the accepted answer not working for me, and no useful error message from pandas. I just came to point out that while the accepted answer may work fine for html, or Jupyter or whatever they're using. It does not work when applied to Excel. For Excel you'll need the following:

new_df.style.apply(
    lambda x: ['background-color: <color>' if x.name in [2,4] else '' for i in x],
    axis=1
)

Note the use of "backgound-color". Excel will not render "background" as you might expect

In addition, when working with Excel, you'll need to use a color name From Excel's list of recognized colors, Fiddling around with the above answer using "lightgreen" may give you black-on-black... probably not what anyone is looking for.

Passementerie answered 16/10, 2020 at 4:6 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.