根据分组依据查找第三列-熊猫

时间:2019-03-05 17:36:36

标签: pandas pandas-groupby

我有三列ID,score1,score2。我需要基于第三个字段创建第四列,并且可以将列ID分组,因为score1和score2是ID的记录。这是桌子。

id  score1 score2
1   6      10
1   5      12
2   11     22
2   3      15   

第四列应包含score1列中的值,条件是它应返回组中score2最大的值。

因此对于上面的表,score3表的值如下所示。

id  score1 score2 score3
1   6      10      5  
1   5      12      5
2   11     22      11
2   3      15      11

3 个答案:

答案 0 :(得分:3)

尝试使用function mobilefix(divswitch) { if (divswitch.matches) { // If media query matches $("#divid").insertAfter("#otherdivid") } else { $("#otherdivid").insertAfter("#divid") } } var divswitch = window.matchMedia("(max-width: 640px)"); window.addEventListener('load', function() { mobilefix(divswitch); }) window.addEventListener('resize', function() { mobilefix(divswitch); })

transform

检查

df['score3']=df.groupby('id').score1.transform('max')
df
Out[411]: 
   id  score1  score2  score3
0   1       5      10       6
1   1       6      12       6
2   2      11      22      11
3   2       3      15      11

答案 1 :(得分:2)

您可以使用:

df.id.map(df.groupby('id').score3.idxmax().map(df.score1))
Out[415]: 
0     5
1     5
2    11
3    11
Name: id, dtype: int64

答案 2 :(得分:2)

使用sort + drop_duplicates来找到要映射的值,每个id然后映射。

s = df.sort_values('score2').drop_duplicates('id', 'last').set_index('id').score1
df['score3'] = df.id.map(s)

   id  score1  score2  score3
0   1       6      10       5
1   1       5      12       5
2   2      11      22      11
3   2       3      15      11
相关问题