1

I have a pandas dataframe where I would like to verify that column A is greater than column B (row wise). I am doing something like

tmp=df['B']-df['A']
if(any( [ v for v in tmp if v > 0])):
   ....

I was wondering if there was better(concise) way of doing it or if pandas dataframe had any such built in routines to accomplish this

1
  • are you just varifying that all values in column A are greater than from coulmn B respectively? if its valid to all respective values it will return True else False? Commented Nov 5, 2019 at 13:13

3 Answers 3

2
df = pd.DataFrame({'A': [1, 2, 3], 'B': [3, 1, 1]})

temp = df['B'] - df['A']

print(temp)

0    2
1   -1
2   -2

Now you can create a Boolean series using temp > 0:

print(temp > 0)

0     True
1    False
2    False
dtype: bool

This boolean series can be fed to any and therefore you can use:

if any(temp > 0):
    print('juhu!')

Or simply (which avoids temp):

if any(df['B'] > df['A']):
    print('juhu')

using the same logic of creating a Boolean series first:

print(df['B'] > df['A'])

0     True
1    False
2    False
dtype: bool
Sign up to request clarification or add additional context in comments.

Comments

1

df['B']>df['A'] will be pandas series in boolean datatype.

 >>> (df['B']>df['A']).dtype
      dtype('bool')

For example

>>> df['B']>df['A']
   0     True
   1    False
   2    False
   3     True
   4     True
   dtype: bool

any() function returns True if any of the item in an iterable is true

>>> if any(df['B']>df['A']):
...     print(True)
... 
     True

1 Comment

"you can try"?? could you please explain your answer?
0

I guess you wanted to check if any df[‘B'] > df[‘A’] then do something.

import pandas as pd
import numpy as np
df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [2, 0, 6, 3]})
if np.where(df['B'] > df['A'], 1, 0).sum():
    print('do something')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.