【问题标题】:getting the group name as a list after groupby在 groupby 之后获取组名作为列表
【发布时间】:2020-04-15 11:17:28
【问题描述】:

我正在使用 python groupby 函数使用两列进行分组

grouped =df.groupby(['col2','col4']).size().groupby(level=0).size()

我得到了输出

col2
item1            1
item2            1
item3            7
item4            6
item5            3
item6            5

我想要 size>3 的组名列表如下:

['item3','item4',item6]

试用代码

list(grouped)

给我数字列表,但不是所需的组名列表。有什么建议吗?

【问题讨论】:

    标签: python pandas list group-by


    【解决方案1】:

    用途:

    [*grouped.loc[lambda x: x > 3].index]
    

    [*grouped[grouped > 3].index]
    

    【讨论】:

      【解决方案2】:

      boolean indexing过滤索引值:

      out = grouped.index[grouped > 3].tolist()
      

      替代方案:

      out = grouped[grouped > 3].index.tolist()
      

      【讨论】:

        猜你喜欢
        • 2020-11-21
        • 2015-05-04
        • 2019-04-09
        • 1970-01-01
        • 2016-02-04
        • 2021-09-30
        • 2016-11-24
        • 2017-03-28
        • 2023-03-29
        相关资源
        最近更新 更多