Check if column value is greater than the max between pandas column and python variable

Viewed 7444

I have a dataframe which looks like this

pd.DataFrame({'A': ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7'],
  ...:                    'x': [2, 2, 3, 2, 3, 1, 3],
  ...:                    'maxValue_1': [2, 1, 2, 3, 4, 2, 1]})
Out[7]: 
    A  x  maxValue_1
0  C1  2           2
1  C2  2           1
2  C3  3           2
3  C4  2           3
4  C5  3           4
5  C6  1           2
6  C7  3           1

maxValue_2 = 2

I need to check whether column 'x' is equal or greater than the max(df.maxValue_1, maxValue_2)

Resulting dataframe should look like this.

    A  x  maxValue_1  result
0  C1  2           2   True
1  C2  2           1   True
2  C3  3           2   True
3  C4  2           3   False
4  C5  3           4   False
5  C6  1           2   False
6  C7  3           1   True

How can I code this in an efficient manner without having to add variable 'maxValue_2' to the dataframe?

5 Answers
df['result'] = df['x'] >= np.maximum(df['maxValue_1'], maxValue_2)
print(df)

Prints:

    A  x  maxValue_1  result
0  C1  2           2    True
1  C2  2           1    True
2  C3  3           2    True
3  C4  2           3   False
4  C5  3           4   False
5  C6  1           2   False
6  C7  3           1    True
df['result'] = df.apply(lambda row: row.x >= max(row.maxValue_1, maxValue_2), axis=1)

I have found that the apply method is extremely useful for this type of problem. We want to apply some function, model_map to the dataframe.

def model_map(row):
    if row['x'] >= max(df.maxValue_1, maxValue_2):
        return True
    else:
        return False
    
df['result'] = df.apply(lambda row : model_map(row), axis=1)

This will give you a nice way to create a column based on a function.

To accomplish this, we’ll use numpy’s built-in where() function. This function takes three arguments in sequence: the condition we’re testing for, the value to assign to our new column if that condition is true, and the value to assign if it is false. It looks like this:

np.where(condition, value if condition is true, value if condition is false)

And the function maximum() to get the max of the giving values:

df['result'] = np.where(df['x']>= np.maximum(df['maxValue_1'], maxValue_2) , True, False)

OUTPUT:

    A  x  maxValue_1  result
0  C1  2           2    True
1  C2  2           1    True
2  C3  3           2    True
3  C4  2           3   False
4  C5  3           4   False
5  C6  1           2   False
6  C7  3           1    True

You can also define the series of maxes through set comprehension and compare to the x series like so

df['result'] = df['x'] >= [ max(max_value2, row['maxValue_1']) for idx, row in df.iterrows()]
Related