datazang
datazang

Reputation: 1169

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?

Upvotes: 0

Views: 339

Answers (3)

user2736738
user2736738

Reputation: 30926

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]

Upvotes: 2

user17242583
user17242583

Reputation:

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

Upvotes: 0

Rivered
Rivered

Reputation: 789

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.

Upvotes: 0

Related Questions