Check corresponding columns for null data

Check corresponding columns for null data

Imagine I have a dataframe like so:

ID, place, stock
1, 1, 4
2, NaN, 2
3, NaN, NaN
4, 1, 1

I wish to find all the rows for which place is null and check the corresponding stock column to see, for instance, if place is Null but stock is >0.

I've implemented this by iterating over the dataframe like so:

for idx, x in enumerate(df[place].isnull().tolist()):
    ...

But I am sure there is a simpler way to do this.

For example, for the above data for each row for which place is null, I wish to check if the corresponding stock column is >0 and count how many occurrences are like so.

In actual fact, I wish to check multiple columns (>10) to see if they meet certain criteria, and so am more interested in a generic solution to this.

Answer

You can use something vectorized like that

count = df[df['place'].isnull() & (df['stock'] > 0)].shape[0]

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles