I was trying to style few cells in pandas dataframe and I would like to define a function that takes arbitrary condition and evaluates it.
Note
There is a similar link Dynamic Expression Evaluation in pandas using pd.eval() which talks about pandas eval and query.
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
Error
NameError: name 'x' is not defined