Python Pandas 按列排序,但保持索引相同

标签 python sorting pandas

我创建了一个由 Country、deal_category 和 some_metric 组成的数据框。

看起来像

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

我使用命令根据国家/地区和 channel 进行索引

df2 = df.set_index(["Country", "channel"])

这将创建以下数据框。

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

Country2    category1   1234

这就是我想做的。我想保持这个结构相同并根据指标计数进行排序。换句话说,我想根据指标计数显示每个国家/地区的前 3 个 channel 。

例如,我希望为每个国家/地区显示一个数据框,按 metric_counts 降序排列前 3 个类别。

Country2    top category1   12355555
            top category2   159393
            top category3   16759

我尝试先排序,然后索引,但生成的数据框不再根据国家/地区进行分区。任何提示将非常感谢。谢谢!

最佳答案

经过一些艰苦的实验,我终于得到了我想要的东西。我在下面概述了我的步骤

  1. 按国家/地区分组

    group = df.groupby("Country")
    

    从高层来看,这表明我们希望以不同的方式看待每个国家。现在我们的目标是确定前 3 个指标计数并报告相应的 channel 。为此,我们将对结果数据框进行排序,然后仅返回前 3 个结果。我们可以通过定义一个仅返回前 3 个结果的排序函数并使用 pandas 中的 apply 函数来做到这一点。这向 panda 表明“我想将此排序函数应用于每个组并返回每个组的前 3 个结果”。

  2. 排序并返回前 3 名

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

关于Python Pandas 按列排序,但保持索引相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31233040/

相关文章:

python - 如何使用 pytest 在测试后*显示测试名称?

python - ValueError : Error getting data from the api, 没有返回。阿尔法优势

c - 执行排序和搜索 C 函数时出错

regex - 在 powershell 中按正则表达式内的命名捕获组排序

python - Pandas 格式符号 xlsx

Pandas Duplicated 返回一些不重复的值?

python - 寻找支持 Python 的在线判断引擎

python - 使用 Flask 和 Python 从配置文件中读取属性

algorithm - 对 4 个数字进行排序,比较少

python - boolean 掩码每行中不同长度的列表