To check Pandas Dataframe column for TRUE/FALSE, if TRUE check another column for condition to satisfy and generate new column with values PASS/FAIL
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping
--
Chapters
00:00 Question
01:19 Accepted answer (Score 3)
01:54 Answer 2 (Score 4)
02:13 Thank you
--
Full question
https://stackoverflow.com/questions/6265...
Accepted answer links:
[numpy.select]: https://numpy.org/doc/stable/reference/g...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #numpy #dataframe #boolean
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping
--
Chapters
00:00 Question
01:19 Accepted answer (Score 3)
01:54 Answer 2 (Score 4)
02:13 Thank you
--
Full question
https://stackoverflow.com/questions/6265...
Accepted answer links:
[numpy.select]: https://numpy.org/doc/stable/reference/g...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #numpy #dataframe #boolean
#avk47
ANSWER 1
Score 5
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)
ACCEPTED ANSWER
Score 3
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