Home > other >  How can I count the nominal data from multiple columns
How can I count the nominal data from multiple columns

Time:11-05

Let's say I have a data that looks like below

df = pd.DataFrame({
'a':["Yes","No", "Yes"], 
'b':["Yes","No", "No"], 
'c':["Yes","Yes", "Yes"], 
'd':["No","Yes", "No"], 
'e':["Yes","No", "Yes"]})

I want to count each Yes from my dataframe and add as new column. The result would look like below.

a b c d e f
0 Yes Yes Yes No Yes 4
1 No No Yes Yes No 2
2 Yes No Yes No Yes 3

Thanks in advance!

CodePudding user response:

You can just do:

df['f'] = df.eq('Yes').sum(axis=1)

Output:

      a   b   c   d   e  f
0   Yes Yes Yes  No Yes  4
1    No  No Yes Yes  No  2
2   Yes  No Yes  No Yes  3
  • Related