Pandas - 如何计算每个组,对于列中的每个值,哪个值的百分比相等且小于该值

时间:2017-12-12 01:36:32

标签: python python-2.7 pandas

假设我有一个像这样的数据框

x = pd.DataFrame({'person':['a','b']*5 , 'rating':[1,3,4,2,4,2,3,4,5,3]})

现在我想计算每个人,每个评分的偏好得分' 。 现在我将评级r的偏好分数定义为

freq of rating where rating <=r  -  freq of rating where rating ==r

例如a具有以下评级

0   a   1
2   a   4
4   a   4
6   a   3
8   a   5

现在例如对于人a

,评分= 4
freq of rating where rating <=4  :  4/5 
freq of rating where rating ==4   : 2/5

所以偏好分数是2/5

如何为该数据框架上的每条记录获得偏好分数。 编辑:也许这使得它更清晰

   person rating    pref_score
        a   1       0.0
        a   4       0.4
        a   4       0.4
        a   3       0.2
        a   5       0.8

2 个答案:

答案 0 :(得分:1)

所以你需要这样的东西?

x.groupby('person').rating.apply(lambda x : (sum(x<=4)-sum(x==4))/len(x))
Out[7]: 
person
a    0.4
b    0.8
Name: rating, dtype: float64

transform

x.groupby('person').rating.transform(lambda x : (sum(x<=4)-sum(x==4))/len(x))
Out[8]: 
0    0.4
1    0.8
2    0.4
3    0.8
4    0.4
5    0.8
6    0.4
7    0.8
8    0.4
9    0.8
Name: rating, dtype: float64

编辑:

x=x.sort_values('person')
x['ref']=x.groupby('person').rating.apply(lambda y : [(sum(y<=x)-sum(y==x))/len(y) for x in y]).apply(pd.Series).stack().values
x
Out[25]: 
  person  rating  ref
0      a       1  0.0
2      a       4  0.4
4      a       4  0.4
6      a       3  0.2
8      a       5  0.8
1      b       3  0.4
3      b       2  0.0
5      b       2  0.0
7      b       4  0.8
9      b       3  0.4

因为你使用的是python 2.7

x['map']=x.person.map(x.groupby('person').rating.apply(list))
x.apply(lambda x : sum(x['rating']<np.array(x['map']))/len(x['map']),1 )

答案 1 :(得分:0)

您可以执行以下操作:

>> x.groupby("person").rating.apply(lambda x: x[x <= 4].count())
person
a    4
b    5

>> x.groupby("person").rating.apply(lambda x: x[x == 4].count())
person
a    2
b    1