根据其他列值分组自定义函数



我有一个数据框架,其中包含按国家分列的调查回复。

country=['Country A','Country A','Country A','Country B','Country B','Country B']
responses=['Agree','Neutral','Disagree','Agree','Neutral','Disagree']
num_respondents=[10,50,30,58,24,23]
example_df = pd.DataFrame({"Country": country, "Response": responses, "Count": num_respondents})

对于每个国家,我想计算分数(#同意-#不同意)/(总受访者)。是否有一种使用groupby或其他pandas函数的干净方法来做到这一点?

也许有帮助:

example_df.groupby('Country').apply(lambda x: (sum(x['Count'][x['Response'] == 'Agree']) 
- sum(x['Count'][x['Response'] == 'Disagree'])) 
/sum(x['Count']))

最新更新