user3447653
user3447653

Reputation: 4158

Count the number of specific values in a pandas dataframe

I have to count the number of 'No' in a dataframe and add that count to a separate column called 'count'.

For example:

 MachineName    Logs   Jobs   Performance
 121            Yes    No      Yes
 123            Yes    No      No
 126            No     No      No

Output:

 MachineName    Logs   Jobs   Performance   Count
 121            Yes    No      Yes          1
 123            Yes    No      No           2          
 126            No     No      No           3

I tried the following code but it does not run as expected.

 condition = (df[['Logs','Jobs','Performance']] == 'No').any(axis=0)

Any help would be appreciated.

Upvotes: 4

Views: 6588

Answers (1)

jezrael
jezrael

Reputation: 862701

Use sum, because boolean mask is converted to int:

df['Count'] = (df[['Logs','Jobs','Performance']] == 'No').sum(axis=1)

print (df)
   MachineName Logs Jobs Performance  Count
0          121  Yes   No         Yes      1
1          123  Yes   No          No      2
2          126   No   No          No      3

Another solution with select all columns without first by iloc:

df['Count'] = (df.iloc[:,1:] == 'No').sum(axis=1)
print (df)
   MachineName Logs Jobs Performance  Count
0          121  Yes   No         Yes      1
1          123  Yes   No          No      2
2          126   No   No          No      3

Upvotes: 4

Related Questions