Python Pandas按列排序,但保留索引sam

2024-05-16 05:24:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个包含国家、交易类别和一些度量的数据框架。在

看起来像

    Country     metric_count    channel
0   Country1    123472          c1
1   Country1    159392          c2
2   Country2    14599           c3
3   Country2    17382           c4

我使用命令根据国家和频道编制索引

^{pr2}$

这将创建以下数据帧。在

            metric_count
Country     channel     
Country1    category1   12347
            category2   159392
            category3   14599
            category4   17382

Country2    category1   1234

这是我想做的。我想保持这个结构不变,并根据度量计数排序。换句话说,我想显示每个国家的前3个频道,基于指标计数。在

例如,我希望为每个国家显示一个数据框,按度量值的降序排列前3个类别。在

Country2    top category1   12355555
            top category2   159393
            top category3   16759

我尝试过先排序,然后索引,但是结果数据帧不再基于国家进行分区。如有任何提示,我们将不胜感激。谢谢!在


Tags: 数据度量topcountchannel国家频道类别
2条回答

使用groupby/apply分别对每个组进行排序,并只选取前三行:

def top_three(grp):
    grp.sort(ascending=False)
    return grp[:3]
df = df.set_index(['channel'])
result = df.groupby('Country', group_keys=False).apply(top_three)

例如

^{pr2}$

收益率

                   metric_count
Country  channel               
Country0 channel3            93
         channel3             0
         channel1             5
Country1 channel0            46
         channel2            86
         channel2            41
Country2 channel0             4
         channel0            51
         channel3            36

经过一些费力的试验,我终于得到了我想要的东西。我概述了我的步骤

  1. Groupby国家

    group = df.groupby("Country")
    

    从高层来看,这表明我们希望以不同的方式看待每个国家。现在我们的目标是确定前3个度量计数并报告相应的通道。为此,我们将对结果数据帧应用排序,然后只返回前3个结果。我们可以定义一个只返回前3个结果的sort函数,并在pandas中使用apply函数。这表示panda“我想将这个排序函数应用于我们的每个组,并返回每个组的前3个结果”。

  2. 排序并返回前3

    sort_function = lambda x: x.sort("metric_count", ascending = False)[:3]
    desired_df = group.apply(sort_function)
    

相关问题 更多 >