我有一个包含调查数据的数据框。它还包含其他几个列,其中包括人口统计数据(如年龄、部门等)和带有评级的列。希望根据评级列的计算向数据框添加一些列
添加列的目的是提供a)获得有利响应的计数b)获得有利响应的百分比(有利响应的数量/该系数中项目的数量)c)获得有利响应的系数级百分比(如果存在属于该系数的具有NaN的任何项目,则为NaN) 下表显示了如何将其应用于指导因素的示例 我想将这一点推广到其他因素,如多样性、领导力和参与度
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
我已经使用了下面的代码,它是有效的,但是,我只能得到fav_count列和fav_perc列用于指导。希望a)获得_agg_perc列,b)将其应用于所有其他因素
#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)
我猜for循环背后的逻辑是a)创建一个评级列列表(见下面的代码),b)创建一个函数来计算计数、有利响应的百分比,在项目级别查找NaN的存在,以及c)创建一个for循环来将该函数应用于评级列
#Create a list made up of rating cols
ratingcollist = ['Coaching_','Communication_','Development_','Diversity_','Engagement_']
ratingcols = df.loc[:, df.columns.str.contains('|'.join(ratingcollist))]
感谢任何形式的帮助,我可以得到,谢谢你
我相信您需要分别处理列表的每个值:
如果将
nan
替换为fav_perc
的word missing输出是错误的,则第二个值应为1
,因为count排除missing值:因此,如果想要使用
Missing
是必要的,请将count
更改为sum
与compare not equalMissing
:通过将列中的NaN值重新编码为“缺失”并应用@jezrael建议的掩码,问题已得到解决
我们可以尝试不使用循环:
输出
相关问题 更多 >
编程相关推荐