输入解释:
我有一个数据框“df”,它包含“空间”和“阈值”列。
Space Threshold
TRUE 0.1
TRUE 0.25
FALSE 0.5
FALSE 0.6
要考虑的场景:当 df['Space'] 为 TRUE 时,检查 df['Threshold']<=0.2,如果两个条件都满足,则生成一个名为 df['Space_Test'] 且值为 PASS/FAIL 的新列。如果 df['Space'] 值为 FALSE,则将 'FALSE' 作为值放入新生成的列 df['Space_Test']。
预期输出:
Space Threshold Space_Test
TRUE 0.1 PASS
TRUE 0.25 FAIL
FALSE 0.5 FALSE
FALSE 0.6 FALSE
尝试过的代码:已经针对上述场景尝试了下面提到的代码行,但不起作用。
df['Space_Test'] = np.where(df['Space'] == 'TRUE',np.where(df['Threshold'] <= 0.2, 'Pass', 'Fail'),'FALSE')
需要帮助来解决这个问题。提前致谢!
最佳答案
如果 TRUE
是 boolean 值,您的解决方案仅通过 df['Space']
比较来简化:
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
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
关于python - 要检查 Pandas Dataframe 列是否为 TRUE/FALSE,如果为 TRUE,则检查另一列是否满足条件并生成具有值 PASS/FAIL 的新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62656422/