Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Count number of values in a column where another column in the data frame is null

Tags:

python

pandas

I have the following dataset df

   UniqueID Col1 Col2
0      1234    5  NaN
1      1235    3    4
2      1233  NaN    3
3      1111    3  NaN

I'd like to know the number of rows where Col1 is not null and Col2 is null.

like image 535
bjurstrs Avatar asked Feb 01 '26 12:02

bjurstrs


2 Answers

(df.Col1.notnull() & df.Col2.isnull()).sum()

2
like image 93
piRSquared Avatar answered Feb 04 '26 00:02

piRSquared


I'd obviously go with PiRSquared's.

If you, however, want to go something fancy with query, then use

In [430]: df.query('Col1 == Col1 & Col2 != Col2').shape[0]
Out[430]: 2
like image 32
Zero Avatar answered Feb 04 '26 00:02

Zero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!