Search code examples
pandasdataframeif-statementconditional-statementsmultiple-columns

New column based on values from other columns in python


I have a dataframe df which looks like this

min max value
3 9 7
3 4 10
4 4 4
4 10 3

I want to create a new column df['accuracy'] which tells me the accuracy if the df['value'] is in between df['min'] and df['max'] such that the new dataframe looks like

min max value Accuracy
3 9 7 Accurate
3 4 10 Not Accurate
4 4 4 Accurate
4 10 3 Not Accurate

Solution

  • Use apply() method of pandas, refer link

    def accurate(row):  
        if row['value'] >= row['min'] and row['value'] <= row['max']:
            return 'Accurate'
        return 'Not Accurate'
    
    df['Accuracy'] = df.apply(lambda row: accurate(row), axis=1)
    print(df)