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
Error
NameError: name 'x' is not defined