针对特定列优化的Pandas行索引

Mec*_*nic 0 python pandas

我有一个示例数据帧如下

   p1   p2  p3  score
0   1   a   t1  0.408718
1   1   a   t2  0.694732
2   1   a   t3  0.001077
3   1   b   t1  0.250646
4   1   b   t2  0.877506
5   1   b   t3  0.033305
6   2   a   t1  0.735524
7   2   a   t2  0.055166
8   2   a   t3  0.579875
9   2   b   t1  0.579199
10  2   b   t2  0.785301
11  2   b   t3  0.339372
Run Code Online (Sandbox Code Playgroud)

p1,p2p3是参数.我想要做的是选择具有p1和p2值的最佳行,其中最大平均得分基于p3.

例如,在给定的数据帧中,此函数应该返回行9,10,11中的任何一行,因为p3得分(0.579199, 0.785301, 0.339372)= 的平均值0.567958是我可以为任何给定的一组p1和得到的最大值p2.

到目前为止我的尝试(使用pandas groupy)如下

temp = []
for eachgroup in df.groupby(['p1', 'p2']).groups.keys():
    temp.append(df.groupby(['p1', 'p2']).get_group(eachgroup)['score'])

temp1 = []
for each in temp:
temp1.append(each.mean())

maxidx = temp1.index(max(temp1))

temp[maxidx].index
Run Code Online (Sandbox Code Playgroud)

返回以下输出

Int64Index([9, 10, 11], dtype='int64')
Run Code Online (Sandbox Code Playgroud)

但是,这效率非常低,仅适用于较小的数据帧.如何为更大的数据帧执行相同的操作?

WeN*_*Ben 6

在你的情况下

s=df.groupby(['p1','p2']).score.transform('mean')
s.index[s==s.max()]
Out[239]: Int64Index([9, 10, 11], dtype='int64')
Run Code Online (Sandbox Code Playgroud)