Reputation: 85
I have a dataframe:
Item SW_test HW_test QA_test
0 PC Pass Pass Pass
1 Laptop Fail Fail Pass
2 Mouse Pass Pass Fail
I want to create a final column which will give Pass
if all tests were pass (not case sensitive) and Fail
if one or more are fail.
Item SW_test HW_test QA_test Final
0 PC Pass Pass Pass Pass
1 Laptop Fail Fail Pass Fail
2 Mouse Pass Pass Fail Fail
How can I create df['Final']
in pandas?
Upvotes: 3
Views: 1285
Reputation: 13255
Use eq
with all
:
df['Final'] = df.iloc[:,1:].eq('Pass').all(1)
#If case sensitive you can use
df['Final'] = df.iloc[:,1:].isin(['Pass','pass']).all(1)
#or
df['Final'] = df.iloc[:,1:].apply(lambda x: x.str.lower().eq('pass')).all(1)
#or
df['Final'] = df.iloc[:,1:].applymap(str.lower).eq('pass').all(1)
Also instead of mapping again True/False using map, you can use np.where
:
df['Final'] = np.where(df['Final'], 'Pass', 'Fail')
Upvotes: 6
Reputation: 14094
cols = ['SW_test', 'HW_test', 'QA_test']
df['Final'] = df[cols].eq('Pass').all(1)
Item SW_test HW_test QA_test Final
0 PC Pass Pass Pass Pass
1 Laptop Fail Fail Pass Fail
2 Mouse Pass Pass Fail Fail
Upvotes: 4
Reputation: 1196
# set column to "Pass" initially
df["Final"] = "Pass"
# set "Fail" rows
df.loc[(
(df.loc[:, ["SW_test", "HW_test", "QA_test"]] == "Fail") |
(df.loc[:, ["SW_test", "HW_test", "QA_test"]] == "fail")
).any(axis = 1), "Final"] = "Fail"
Upvotes: 0
Reputation: 801
You can apply lambda function to check where the condition holds and then can replace the true/false value with whatever you want. For example:
#create a dataframe
df = pd.DataFrame({'a':['Pass','Pass'], 'b':['Pass','Fail']})
a b
0 Pass Pass
1 Pass Fail
Create a new column where the condition holds
df['c'] = df.apply(lambda row: row.a=='Pass' and row.b=='Pass', axis=1)
a b c
0 Pass Pass True
1 Pass Fail False
Replace the true/false values with what you want to display
df['c'] = df['c'].map({ True: 'Pass', False: 'Fail'})
a b c
0 Pass Pass Pass
1 Pass Fail Fail
Upvotes: 1