Python version of R's ifelse statement

if-statement, pandas, python, r

Solution

The equivalent is `np.where`:

import numpy as np
np.where(df['A'] < 1, -df['X'], df['X'])

This checks if the values in column `A` are lower than 1. If so, it returns the corresponding value multiplied by -1 from `df['X']`, otherwise it returns the corresponding value in `df['X']`.

That said, your error/warning is probably raised because of chained indexing. Instead of `df['X'][df['A'] <1]` you should use `df.loc[df['A'] <1, 'X']`. Then you can do the same with two steps as you have shown in the question.

Problem

I am trying to learn Python after learning R and an simple ifelse statement. In R I have: ``` df$X <- if(df$A == "-1"){-df$X}else{df$X} ``` But I am unsure how to implement it in Python, I have tried: ``` df['X'][df['A'] <1] = -[df['X'] df['X'][df['A'] >1] = [df['X'] ``` But this leads to errors, would appreciate some help.

Original source