1# Syntax:
2# C = np.where(condition, A, B)
3# equal to A when condition true and B when false
4import numpy as np
5import pandas as pd
6
7a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]
8df = pd.DataFrame(a, columns=['one', 'two', 'three'])
9
10df['que'] = np.where((df['one'] >= df['two']) & (df['one'] <= df['three'])
11 , df['one'], np.nan)
12
13# If you have more than one condition, then you could use np.select
14# instead. For example, if you wish df['que'] to equal
15# df['two'] when df['one'] < df['two'], then
16conditions = [
17 (df['one'] >= df['two']) & (df['one'] <= df['three']),
18 df['one'] < df['two']]
19
20choices = [df['one'], df['two']]
21
22df['que'] = np.select(conditions, choices, default=np.nan)
23
24# If we can assume that df['one'] >= df['two'] when
25# df['one'] < df['two'] is False, then the conditions and
26# choices could be simplified to
27conditions = [
28 df['one'] < df['two'],
29 df['one'] <= df['three']]
30
31choices = [df['two'], df['one']]
32
33# Note that:
34a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]
35df = pd.DataFrame(a, columns=['one', 'two', 'three'])
36
37# defines a DataFrame with string values. Since they look numeric,
38# you might be better off converting those strings to floats:
39df2 = df.astype(float)
40
41# This changes the results, however, since strings compare
42# character-by-character, while floats are compared numerically.
43
44
45
46
1df['Result'] = (df.iloc[:, 1:4].values < df[['E']].values).all(axis=1).astype(int)
2print (df)
3 A B C D E Result
40 V 10 5 18 20 1
51 W 9 18 11 13 0
62 X 8 7 12 5 0
73 Y 7 9 7 8 0
84 Z 6 5 3 90 1
9