'How to count the rows with the conditions?

I have a data set something like this:

import pandas as pd
 
# initialize data of lists.
data = {'name':['x', 'y', 'z'],
        'value':['fb', 'nan', 'ti']}
 
# Create DataFrame
df = pd.DataFrame(data)

I now want to check the column of value and count the number of rows if value does not have 'fb' and 'nan' (null values).

How can I do this?



Solution 1:[1]

df[~df.value.isin(['fb','nan'])].shape[0]

In this case, we are checking when the value is not in this list and selecting those rows only. From there we can get the shape using shape of that dataframe.

Output

1

This would be the result dataframe

  name value
2    z    ti

If in future you want to also ignore the rows where the value column is NA (NA values, such as None or numpy.NaN),then you can use this

df[(~df.value.isin(['fb','nan'])) &  (~df.value.isnull())].shape[0]

Solution 2:[2]

To count values that are not fb and nan:

(~df.value.str.contains('fb|nan')).sum()

Omit the tilde if you want to count the fb and nan values.

Solution 3:[3]

Just make a condition checking for "fb" or NaN, and use sum to get the count of True's:

>>> (df['value'].eq('fb') | df['value'].isna()).sum()
3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Rivered
Solution 3 richardec