I have pandas dataframe of the form,df=
index,result1,result2,result3
0 s u s
1 u s u
2 s
3 s s u
i would like to add another column that contains a list of the number of times s occurs in that row, for example
index,result1,result2,result3,count
0 s u s 2
1 u s u 1
2 s 1
3 s s u 2
i have tried the following code
col=['result1','result2','result3']
df[cols].count(axis=1)
but this returns
0,3
1,3
2,1
3,3
so this counts the number of elements, i then tried
df[df[cols]=='s'].count(axis=1)
but this returned the following error: "Could not compare ['s'] with block values"
Any help would be greatly appreciated
NaN? what doesdf.info()show?df=='s'will work if you have all str or mixed dtypes but if you have any pure numerical columns or rows then this won't work, this will happen if you have any rows with allNaNYou can trydf.fillna('', inplace=True)then(df[cols] = 's').count(axis=1)should workdf['count'] = (df[cols].values=='s').sum(1)would be a nice alternative?