【问题标题】:Select top n columns based on another column根据另一列选择前 n 列
【发布时间】:2020-12-30 03:17:25
【问题描述】:

我有一个数据库如下:

我想获得一个熊猫数据框,根据人口最多的前几行过滤每个日期的 2 行。输出应如下所示:

我知道 pandas 提供了一个名为 nlargest 的公式: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.nlargest.html

但我认为它不适用于这个用例。有什么解决办法吗?

提前非常感谢!

【问题讨论】:

  • 也许你可以sort_values['Date', 'Population'])并使用groupby'Date')?
  • 最好将数据粘贴为帖子的一部分而不是图像。它可以帮助人们测试您的数据并给出正确的答案。随时将代码或数据作为图像放置是不好的做法
  • @iraciv94 ,如果你喜欢这个答案,那么你也可以投票✔????

标签: python-3.x pandas sorting filtering


【解决方案1】:

我模仿了您的数据框如下,并提供了一种获得所需的方法,希望对您有所帮助。

您的数据框:

>>> df
        Date country  population
0 2019-12-31       A         100
1 2019-12-31       B          10
2 2019-12-31       C        1000
3 2020-01-01       A         200
4 2020-01-01       B          20
5 2020-01-01       C        3500
6 2020-01-01       D          12
7 2020-02-01       D        2000
8 2020-02-01       E          54

您想要的解决方案:

您可以将nlargest 方法与set_indexgroupby 方法一起使用。

这就是你将得到的......

>>> df.set_index('country').groupby('Date')['population'].nlargest(2)
Date        country
2019-12-31  C          1000
            A           100
2020-01-01  C          3500
            A           200
2020-02-01  D          2000
            E            54
Name: population, dtype: int64

现在,您希望通过重置 DataFrame 的索引将 DataFrame 恢复到原始状态,这将为您提供以下 ..

>>> df.set_index('country').groupby('Date')['population'].nlargest(2).reset_index()
        Date country  population
0 2019-12-31       C        1000
1 2019-12-31       A         100
2 2020-01-01       C        3500
3 2020-01-01       A         200
4 2020-02-01       D        2000
5 2020-02-01       E          54

另一种方式:

使用groupbyapply 函数使用reset_index 和参数drop=Truelevel= ..

>>> df.groupby('Date').apply(lambda p: p.nlargest(2, columns='population')).reset_index(level=[0,1], drop=True)
  # df.groupby('Date').apply(lambda p: p.nlargest(2, columns='population')).reset_index(level=['Date',1], drop=True)
        Date country  population
0 2019-12-31       C        1000
1 2019-12-31       A         100
2 2020-01-01       C        3500
3 2020-01-01       A         200
4 2020-02-01       D        2000
5 2020-02-01       E          54

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多