Input Explained: I have a dataframe 'df', which holds columns 'Space' and 'Threshold'.
Space Threshold
TRUE 0.1
TRUE 0.25
FALSE 0.5
FALSE 0.6
Scenario to consider: When df['Space'] is TRUE, check df['Threshold']<=0.2 and if both condition satisfies generate a new column called df['Space_Test'] with value PASS/FAIL. If df['Space'] value is FALSE, put 'FALSE' as value to newly generated column df['Space_Test'].
Expected Output:
Space Threshold Space_Test
TRUE 0.1 PASS
TRUE 0.25 FAIL
FALSE 0.5 FALSE
FALSE 0.6 FALSE
Tried Code: Have tried out the below mentioned codeline for above mentioned scenario but doesn't works.
df['Space_Test'] = np.where(df['Space'] == 'TRUE',np.where(df['Threshold'] <= 0.2, 'Pass', 'Fail'),'FALSE')
In need of help to resolve this. Thanks in Advance!
Another solution
from pandas import DataFrame
names = {
'Space': ['TRUE','TRUE','FALSE','FALSE'],
'Threshold': [0.1, 0.25, 1, 2]
}
df = DataFrame(names,columns=['Space','Threshold'])
df.loc[(df['Space'] == 'TRUE') & (df['Threshold'] <= 0.2), 'Space_Test'] = 'Pass'
df.loc[(df['Space'] != 'TRUE') | (df['Threshold'] > 0.2), 'Space_Test'] = 'Fail'
print (df)
If TRUE
are boolean your solution is simplify by compare by df['Space']
only:
df['Space_Test'] = np.where(df['Space'],
np.where(df['Threshold'] <= 0.2, 'Pass', 'Fail'),'FALSE')
print (df)
Space Threshold Space_Test
0 True 0.10 Pass
1 True 0.25 Fail
2 False 0.50 FALSE
3 False 0.60 FALSE
Alternative with numpy.select
:
m1 = df['Space']
m2 = df['Threshold'] <= 0.2
df['Space_Test'] = np.select([m1 & m2, m1 & ~m2], ['Pass', 'Fail'],'FALSE')
print (df)
Space Threshold Space_Test
0 True 0.10 Pass
1 True 0.25 Fail
2 False 0.50 FALSE
3 False 0.60 FALSE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With