我有一个数据帧,看起来像以下对象:应用功能GROUPBY在python熊猫
id salary days_employed category salary_percentile
1 200000 400 1 14
其中0类表示自己是一个早期半途而废和1说,他一直保持更长的时间。
我的代码如下:
df1['salary_percentile'] = pd.qcut(df1['salary'], 50, labels=['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50'])
切割INTP 50水桶和检查落在第37 salary_percentile行之后,这是我的数据框的样子: [在这里输入的形象描述] [ 2] [2]
def f(x):
early_quitter = x.loc[(x.category== '0')]
non = x.loc[(x.category == '1')]
proportion_early_quitters = early_quitter.shape[0]/x.shape[0]
return pd.Series({'prop_early_quitters': proportion_early_quitters})
bypercentile = df1.groupby('salary_percentile').apply(f)
bypercentile = bypercentile.reset_index(level='None')
bypercentile
我希望我的函数返回一个包含early_quitters的每一个组中的比例数据帧。即在每个组中,我想计算(len(early_quitter)/ len(group))。 当我使用这个函数时,它为每个组返回一个0比例的数据帧。
有人可以帮助我吗?
在旁注中,我使用上面显示的代码创建了salary_percentile列。
谢谢!
定义的变量是你得到这个使用Python 2?如果是这样,请尝试将'from __future__ import division'放在代码的开头。 – BrenBarn
非常感谢!它为我工作!我确实使用Python 2!再次感谢!! – Gingerbread