Reputation: 4158
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
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