熊猫基于行值的新列

时间:2020-08-03 15:13:33

标签: python pandas

我有一个数据框:

    Item    SW_test HW_test QA_test
0   PC      Pass    Pass    Pass
1   Laptop  Fail    Fail    Pass
2   Mouse   Pass    Pass    Fail

我想创建一个最后一列,如果所有测试均通过(不区分大小写),则将显示Pass,如果一个或多个测试失败,则显示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

如何在熊猫中创建df['Final']

4 个答案:

答案 0 :(得分:6)

eqall一起使用:

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)

您也可以使用np.where

df['Final'] = np.where(df['Final'], 'Pass', 'Fail')

答案 1 :(得分:3)

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

答案 2 :(得分:1)

您可以应用lambda函数检查条件的位置,然后可以使用所需的值替换true / false值。 例如:

#create a dataframe
df = pd.DataFrame({'a':['Pass','Pass'], 'b':['Pass','Fail']})


    a       b
0   Pass    Pass
1   Pass    Fail

在条件成立的地方创建一个新列

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

将true / false值替换为要显示的内容

df['c'] = df['c'].map({ True: 'Pass', False: 'Fail'})


    a       b       c
0   Pass    Pass    Pass
1   Pass    Fail    Fail

答案 3 :(得分:0)

# 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"