I have a dataframe with survey data. It contains several other columns with demographic data (eg age, department etc) and the columns with ratings. Would like to add some columns to the dataframe based on calculations of the ratings columns.
The purpose of adding the columns is to provide a) get a count of Favourable responses b) get the percentage of Favourable responses (no of favourable responses / no of items in that factor) c) get the factor level percentage of Favourable responses (where it will be NaN if there are any items with NaN that belong to the factor) The table below shows an example of how it will be applied to the Coaching Factor Would like to replicate this for the other Factors like Diversity, Leadership, Engagement.
Coach_q1 Coach_q2 Coach_q8 coach_favcount coach_fav_perc coach_agg_perc
Favourable Neutral Favourable 2 66.6% 66.6%
Favourable Favourable NaN 2 100% NaN
Favourable Favourable Unfavourable 2 66.6% 66.6%
NaN NaN Unfavourable 0 0% NaN
I've used the following code and it works, however, am only able to get the fav_count column and the fav_perc column for Coaching. Would like a) get the _agg_perc column and b) apply this to all other Factors.
#Get the Coaching Columns
coaching_agg = df.loc[:, df.columns.str.contains('Coaching_')]
#Create a column to store the number of favourable responses
df['coaching_fav_count'] = df[coaching_cols == 'Favourable'].notna().sum(axis=1)
#create a column to store the percentage of favourable responses
df['coaching_fav_perc'] = df['coaching_fav'] / len(coaching_agg.columns)
Im guessing the logic behind the for loop would be to a) create a list of the rating columns (see code below) and b) create a function to calculate the counts, percentages of favourable responses, look for presence of NaN at the item level and c) create a for loop to apply the function to the rating columns.
#Create a list made up of rating cols
ratingcollist = ['Coaching_','Communication_','Development_','Diversity_','Engagement_']
ratingcols = df.loc[:, df.columns.str.contains('|'.join(ratingcollist))]
Appreciate any form of help that i can get, thank you!