Efficient way to count string values across multiple columns to create new total column

Viewed 153

I have a dataframe of survey responses with 'Yes/No' responses. I would like to create a new column/variable that is the total number of Yes responses.

enter image description here

I could replace all the 'Yes/No' to '1/0', then use:

df['total_variable'] = df.iloc[:, 16:22].sum(axis=1)

Or I could write a for loop.

But I was just wondering if there are any other efficient ways of doing this?

1 Answers

Instead replacing compare by Yes by DataFrame.eq and then count Trues by sum:

df['total_variable'] = df.iloc[:, 16:22].eq('Yes').sum(axis=1)
Related