I have a dataframe and I want to count how many times a string (say 'Yes') has occurred in all other columns. I want to add count into new column and call it 'Yes-Count'.
I have it working using lamda and following example Creating a new column based on if-elif-else condition
I am curious if this can be done in one line.
This is sample data and code.
import pandas as pd
def finalCount(row):
count = 0
if row['Col1'] == 'Yes':
count = count + 1
if row['Col2'] == 'Yes':
count = count + 1
if row['Col3'] == 'Yes':
count = count + 1
if row['Col4'] == 'Yes':
count = count + 1
return count
data = {
'Col1': ['Yes', 1, 'No', 'Yes'],
'Col2': ['Yes', 2, 'No', 'Yes'],
'Col3': ['No', 3, 'Yes', 'Yes'],
'Col4': ['Yes', 4, 'No', 'Yes'],
}
dfData = pd.DataFrame(data, columns= ['Col1','Col2','Col3','Col4'])
dfData['Yes-Count'] = dfData.apply(finalCount, axis =1)
I get result as expected.
Is there a way to get rid of finalCount method and do this in one line?