Pandas,从数据框中的子列获得最大和第二位

时间:2017-01-12 13:56:33

标签: python pandas

我有以下DataFrame:

    usersidid   clienthostid    LoginDaysSum    
0       12            1             240     
1       11            1             60  
3       5             1             5       
4       6             3             2702    
2       10            3             423     
5       8             3             18      

每个clienthostid都有带有LoginDaysSum的usersidid。 df已分类

df.sort_values(['clienthostid', 'LoginDaysSum'], ascending=[True, False], inplace=True)

现在,我需要的是每个clienthostid是获取他的最大LoginDaysSum,aka,first_place和他的second_place并计算(first_place / second_place)

例如 - usersidid = 1:

first_place = 240
second_place = 60
(first_place/second_place) = 4

我该怎么做?我尝试了一些方法,但我找不到任何东西来访问同一列中的不同成员,如:

df['clienthostid'].apply(x: x.max() / x.one_index_lower_from_max())

非常感谢任何建议,

谢谢,

3 个答案:

答案 0 :(得分:3)

我认为您可以使用groupby并为ilociat选择的每个除以第一和第二个值:

df.sort_values(['clienthostid', 'LoginDaysSum'], ascending=[True, False], inplace=True)

df = df.groupby(['clienthostid'], sort=False)['LoginDaysSum']
       .apply(lambda x: x.iloc[0] / x.iloc[1])

print (df)
clienthostid
1    4.000000
3    6.387707
Name: LoginDaysSum, dtype: float64

答案 1 :(得分:3)

<td id="dynamically-Generate"> (you need to verify that TD id need to be equal in .rowSpan ="here" inside script  )

答案 2 :(得分:3)

使用Groupby.nlargest计算每组最高2个最大值的另一种方法。通过将第二个最大元素移动一个位置到顶部来划分元素,使其与第一个最大值对齐。

通过在level=1之间广播它们,然后从level=0分组的每个组中的第一个项目来完成。

grp = df.groupby('clienthostid').LoginDaysSum
grp.nlargest(2).div(grp.shift(-1), level=1).groupby(level=0).first()

clienthostid
1    4.000000
3    6.387707
Name: LoginDaysSum, dtype: float64

另一个等效变体:

grp = df.groupby('clienthostid').LoginDaysSum.nlargest(2)
grp.div(grp.shift(-1)).groupby(level=0).nth(0)

clienthostid
1    4.000000
3    6.387707
Name: LoginDaysSum, dtype: float64

由于 LoginDaysSum 已经预先按降序排序,因此调用nlargest似乎是一个相当多余的操作。或者,.head(2)实际上就足够了,也会产生更快的结果。

然后我们将偶数行索引位置中的每个值除以它们的下一个奇数索引位置值。

grp = df.groupby('clienthostid').LoginDaysSum.head(2)
pd.Series(grp.iloc[::2].values/(grp.iloc[1::2].values), df.clienthostid.unique())

1    4.000000
3    6.387707
dtype: float64