3

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

enter image description here

Error

NameError: name 'x' is not defined
halfer
  • 19,824
  • 17
  • 99
  • 186
BhishanPoudel
  • 15,974
  • 21
  • 108
  • 169
  • Why the `for v in x`? are you trying to format every column in the row? – dang Jul 11 '20 at 20:43
  • No, only the value 3 in index row called 2 (third row of dataframe). Also, the cond is arbitrary it can be anything. eg. `v>3 and v<20` – BhishanPoudel Jul 11 '20 at 20:44
  • Any reason you don't want to just pass the condition as a function or list of functions? – BallpointBen Jul 11 '20 at 21:09
  • I have no preoccupied reasons, you can implement whatever method you like. – BhishanPoudel Jul 11 '20 at 21:11
  • 2
    See [Dynamic Expression Evaluation in pandas using pd.eval()](https://stackoverflow.com/questions/53779986/dynamic-expression-evaluation-in-pandas-using-pd-eval) for the various implementations of evaluating an expression with a dataframe. – Trenton McKinney Jul 11 '20 at 22:32
  • @TrentonMcKinney I am aware with `pd.eval `and `df.query`, but here I am struggling to find a way to implement that idea here inside df.style function. If you post the complete, I would greatly appreciate your effort. – BhishanPoudel Jul 12 '20 at 00:26
  • Can you provide some data as text and expected output for the expression shown? – cs95 Jul 12 '20 at 05:53
  • @cs95 I need a function `mystyle(df1,cond)` that gives output like **EXPECTED OUTPUT**. – BhishanPoudel Jul 12 '20 at 13:34

0 Answers0