I am trying to conditionally format a pandas dataframe and writing the output to excel. I am stuck at a point:
import pandas as pd
df = pd.DataFrame([['x',3,1],['x',2,2,],['y',4,6]],columns=list("ABC"))
def highlight_rows(row):
value = row.loc['A']
if value in ('x'):
color = '#BAFFC9'
else:
color = None
return ['background-color: {}'.format(color) for r in row]
df.style.apply(highlight_rows,axis=1)
The above code will highlight all rows where the value in column A == 'x'. However, what I want to do is something like: if column A == 'x' then highlight column B else if column A == 'y' then highlight column C else None
I tried combining the above code by writing another function to highlight columns, but that does not seem to work.
def highlight_cols(col):
if col.name == 'B':
color = '#BAFFC9'
else:
color = None
return ['background-color: {}'.format(color) for c in col]
#Call to both the above functions is below
df.style.apply(highlightrows,axis=1).apply(highlight_cols,subset=['B])
Any pointers will be appreciated.
CodePudding user response:
You can try the following approach to conditionally highlight the rows and columns in your dataframe:
import pandas as pd
df = pd.DataFrame([['x',3,1],['x',2,2,],['y',4,6]],columns=list("ABC"))
def highlight_rows_cols(row):
value = row.loc['A']
if value == 'x':
color = '#BAFFC9'
return ['background-color: {}'.format(color) for _ in row[1:2]]
elif value == 'y':
color = '#BAFFC9'
return ['background-color: {}'.format(color) for _ in row[2:3]]
else:
return ['background-color: {}'.format(None) for _ in row]
df.style.apply(highlight_rows_cols, axis=1)
The above code will highlight column B if the value in column A is 'x' and column C if the value in column A is 'y'. Otherwise, it will not highlight any columns.
CodePudding user response:
my approach is try to find by column and row for the highlight column.
import pandas as pd
df = pd.DataFrame([['x',3,1],['x',2,2,],['y',4,6]],columns=list("ABC"))
def highlight_rows(row):
lst = []
value = row.loc['A']
for col in row.index:
if value in ('x') and col == 'B':
lst.append('background-color: #BAFFC9')
continue
if value in ('y') and col == 'C':
lst.append('background-color: #BAFFC9')
continue
lst.append('background-color: None')
return lst
df.style.apply(highlight_rows,axis=1)