Python 要检查Dataframe列是否为TRUE/FALSE,如果为TRUE,请检查另一列是否满足条件,并生成值为PASS/FAIL的新列
输入说明: 我有一个数据帧'df',它包含'Space'和'Threshold'列Python 要检查Dataframe列是否为TRUE/FALSE,如果为TRUE,请检查另一列是否满足条件,并生成值为PASS/FAIL的新列,python,pandas,numpy,dataframe,boolean,Python,Pandas,Numpy,Dataframe,Boolean,输入说明: 我有一个数据帧'df',它包含'Space'和'Threshold'列 Space Threshold TRUE 0.1 TRUE 0.25 FALSE 0.5 FALSE 0.6 要考虑的场景: 当df['Space']为真时,检查df['Threshold']如果TRUE为布尔值,则您的解决方案仅通过比较df['Space']简化: df['Space_Test'] = np.where(df['Space'],
Space Threshold
TRUE 0.1
TRUE 0.25
FALSE 0.5
FALSE 0.6
要考虑的场景:
当df['Space']为真时,检查df['Threshold']如果
TRUE
为布尔值,则您的解决方案仅通过比较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
另一个解决方案
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)
从导入数据帧
姓名={
“空格”:[“真”、“真”、“假”、“假”],
“阈值”:[0.1,0.25,1,2]
}
df=DataFrame(名称、列=['Space','Threshold'])
df.loc[(df['Space']='TRUE')&(df['Threshold']0.2),'Space\u Test']='Fail'
打印(df)
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
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
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)