熊猫,从数据帧中的子列中获得最大值和第二名



我有以下数据帧:

    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都有useridid with LoginDaysSum。DF 已排序

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

现在,我需要的是每个客户端主机ID获取他的最大LoginDaysSum,也就是first_place和他的second_place并计算(first_place/second_place)

例如 - 用户 idid = 1:

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

我到底该怎么做?我尝试了几种方法,但找不到任何可以访问同一列中不同成员的方法,例如:

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

将不胜感激任何建议,

谢谢

print(
    df.groupby('clienthostid')
      .LoginDaysSum.nlargest(2)
      .sort_values()
      .groupby(level=0)
      .pct_change().dropna().add(1)
      .reset_index(1, drop=True)
)
clienthostid
1    4.000000
3    6.387707
Name: LoginDaysSum, dtype: float64
我认为

您可以使用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

另一种使用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

最新更新