pandas2 icon indicating copy to clipboard operation
pandas2 copied to clipboard

A better vectorized ternary operator

Open wesm opened this issue 8 years ago • 3 comments

I was poking around pandas to see if someone had implemented the equivalent of a vectorized if-then-else. For example, similar to np.where, but pandas friendly

df['category'].isin(values).ifelse(df.group_a, df.group_b)

I put this here as it will be easier to implement later (in theory)

wesm avatar Aug 31 '16 03:08 wesm

This is exactly what DataFrame.where already does, e.g., df.group_a.where(df['category'].isin(values), df.group_b)

The name and order of arguments true_case.where(condition, false_case) is obviously not very intuitive, though. So I would strongly support adding an DataFrame.ifelse method or maybe even adding a function (gasp!) pd.ifelse or pd.where with the arguments in the expected order.

shoyer avatar Sep 01 '16 15:09 shoyer

@shoyer the problem with Series.where is that it presumes you have a Series on the LHS. For example, you might want:

cond.ifelse('foo', cond2.ifelse(df.other_col, 'bar'))

wesm avatar Sep 01 '16 17:09 wesm

Indeed, that is a good case for making it a function.

shoyer avatar Sep 01 '16 17:09 shoyer