-1

Note

Similar link Dynamic Expression Evaluation in pandas using pd.eval()

This link talks about df.eval and df.query but does not directly solve this problem.

MWE

import numpy as np
import pandas as pd
import seaborn as sns

df = sns.load_dataset('titanic')
df1 = df.head()

def mystyle(df, cond,x=None,v=None):
    return df.style.apply(lambda x: ["background: salmon"
                            if eval(cond) # eval(cond) exec(cond)
                            else ""
                            for v in x], axis = 1)

cond = "x.name == 2 and v == 3"

# Note: the arbitrary condition only involves two variables x (pandas series) and v (value)
mystyle(df1,cond)

Question

How to implement the function mystyle(df,cond) that gives output

enter image description here

Error

NameError: name 'x' is not defined
halfer
  • 19,824
  • 17
  • 99
  • 186
BhishanPoudel
  • 15,974
  • 21
  • 108
  • 169

1 Answers1

0

Here is my 10 cents:

import numpy as np
import pandas as pd

def f(x,cond='',c='lightgreen'):
    attr = f'background-color: {c}'
    df1 = x.astype(str).replace(x, '')
    df1 = df1.astype(str).replace('nan','')
    df1[eval(cond)] = attr

    return df1

cond = "x[x.index==2]==3"
df1.style.apply(f,axis=None,cond=cond)

output

enter image description here

BhishanPoudel
  • 15,974
  • 21
  • 108
  • 169