numpy.where() with 3 or more conditions

numpy, pandas, python, where-clause

Solution

My understanding is that you need the maximum of columns which are less than the first column, with the fall-back on the first column if no such column exists; if that is the case:

>>> df
          A         B         C         D
0  1.587878 -2.189620  0.631958 -0.432253
1 -1.636721  0.568846 -0.033618 -0.648406
2  1.567512  1.089788  0.489559  1.673372
3  0.589222 -1.176961 -1.186171  0.249795
4  0.366227  1.830107 -1.074298 -1.882093

[5 rows x 4 columns]
>>> df[df.lt(df.A, axis=0)].max(axis=1).fillna(df.A)
0    0.631958
1   -1.636721
2    1.089788
3    0.249795
4   -1.074298
dtype: float64

Problem

I have a dataframe with multiple columns. ``` AC BC CC DC MyColumn ``` A B C D I would like to set a new column "MyColumn" where if BC, CC, and DC are less than AC, you take the max of the three for that row. If only CC and DC are less than AC, you take the max of CC and DC for that row, etc etc. If none of them are less than AC, MyColumn should just take the value from AC. How would I do this with numpy.where()?

Original source