Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare same row in different column with python?

For Example:

I have columns A and B, and I need to do a quality check to make sure that Column B is Null every time Column A is 'Cash'. I don't wan't it to output every row, I just want to know (True/False) if Column B is Null for every time Column A is 'Cash'.

My current (not working) code:

mylist = []

while [df['A'] == 'Cash'] and [df['B'] is None]:

    mylist.append('Pass')
else: 

    mylist.append('Fail')

if 'Fail' in mylist:

     print 'Column A Pass'

else:

     print 'Column A Pass'
like image 606
Window Avatar asked Jun 05 '26 19:06

Window


2 Answers

if Column B is Null for every time Column A is 'Cash'?

aCash = df.A == "Cash"
bNull = df.B.isnull()

aCash.sum() == (aCash & bNull).sum()  
  • aCash & bNull gives Trues if both A is "Cash" and "B" is NULL if it has the same number of Trues as aCash itself it means for all rows where A is Cash, B is NULL.
like image 117
Psidom Avatar answered Jun 07 '26 08:06

Psidom


test equality of conditions

d1.A.eq('Cash').eq(d1.B.isnull()).all()

demo

d1 = pd.DataFrame(dict(
        A=['a', 'b', 'Cash', 'c', 'Cash', 'd'],
        B=[1, 1, None, 1, None, 1],
        C=[1, None, 1, 1, 1, 1]
    ))
print(d1)

      A    B    C
0     a  1.0  1.0
1     b  1.0  NaN
2  Cash  NaN  1.0
3     c  1.0  1.0
4  Cash  NaN  1.0
5     d  1.0  1.0

d1.A.eq('Cash').eq(d1.B.isnull()).all()

True

d1.A.eq('Cash').eq(d1.C.isnull()).all()

False
like image 27
piRSquared Avatar answered Jun 07 '26 07:06

piRSquared