Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional method chaining in pandas

Is there a simple general way to make a method conditional to an if-statement when using method chaining with pandas?

Mock example:

df = pd.DataFrame({'A':['one', 'two'], 'B':['one', 'two']})

change_to_numeric = False

df = (df
    .query("A == 'one'")
    .replace('one', 1)         # <-- Execute this row only "if change_to_numeric == True"
)

Thank you!

like image 489
NJL Avatar asked Aug 29 '26 04:08

NJL


1 Answers

You can use pipe:

df = pd.DataFrame({'A':['one', 'two'], 'B':['one', 'two']})

change_to_numeric = False

df = (df
    .query("A == 'one'")
    .pipe(lambda d: d.replace('one', 1) if change_to_numeric else d)
)

output for change_to_numeric = False:

     A    B
0  one  one

output for change_to_numeric = True:

   A  B
0  1  1
like image 57
mozway Avatar answered Aug 30 '26 20:08

mozway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!