Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count occurrences of stings in a row Pandas

I'm trying to count the number of instances of a certain sting in a row in a pandas dataframe.

In the example here I utilized a lambda function and pandas .count() to try and count the number of times 'True' exists in each row.

Though instead of a count of 'True' it is just returning a boolean whether or not it exists in the row...

#create dataframe 
d = {'Period': [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], 
'Result': ['True','None','False','True','False','True','False','True','True','False','False','True','False','True','False','False'],
'Result1': ['True','None','False','True','False','True','False','True','True','False','False','True','False','True','False','False'],
'Result2': ['True','None','False','True','False','True','False','True','True','False','False','True','False','True','False','False']}
df = pd.DataFrame(data=d)
#count instances of Trus or False in each row
df['Count'] = df.apply(lambda row: row.astype(str).str.count('True').any(), axis=1)
print(df)

The desired outcome is:

Period  Result  Result1 Result2 Count
   1    True    True    True      3
   2    None    None    None      0
   3    False   False   False     0
   4    True    True    True      3
   1    False   False   False     0
   2    True    True    True      3
   3    False   False   False     0
  ...    ...     ...     ...    ......
like image 507
John Conor Avatar asked Jan 30 '26 05:01

John Conor


1 Answers

You can use np.where:

df['count'] = np.where(df == 'True', 1, 0).sum(axis=1)

Regarding why your apply returns a boolean: both any and all returns boolean, not numbers

Edit: You can include df.isin for multiple conditions:

df['count'] = np.where(df.isin(['True', 'False']), 1, 0).sum(axis=1)
like image 83
Nuri Taş Avatar answered Feb 01 '26 21:02

Nuri Taş