The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping

--

Chapters
00:00 To Check Pandas Dataframe Column For True/False, If True Check Another Column For Condition To Satis
01:04 Answer 1 Score 5
01:09 Accepted Answer Score 3
01:30 Thank you

--

Full question
https://stackoverflow.com/questions/6265...

--

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