pandas multiple conditions based on multiple columns using np.where pandas multiple conditions based on multiple columns using np.where pandas pandas

pandas multiple conditions based on multiple columns using np.where


Selection criteria uses Boolean indexing:

df['color'] = np.where(((df.A < borderE) & ((df.B - df.C) < ex)), 'r', 'b')>>> df   A   B   C color0  0  11  20     r1  1  12  19     r2  2  13  18     r3  3  14  17     b4  4  15  16     b5  5  16  15     b6  6  17  14     b7  7  18  13     b8  8  19  12     b9  9  20  11     b


wrap the IF in a function and apply it:

def color(row):    borderE = 3.    ex = 0.    if (row.A > borderE) and( row.B - row.C < ex) :        return "somestring"    else:        return "otherstring"df.loc[:, 'color'] = df.apply(color, axis = 1)

Yields:

  A   B   C        color0  0  11  20  otherstring1  1  12  19  otherstring2  2  13  18  otherstring3  3  14  17  otherstring4  4  15  16   somestring5  5  16  15  otherstring6  6  17  14  otherstring7  7  18  13  otherstring8  8  19  12  otherstring9  9  20  11  otherstring