【问题标题】:Split pandas dataframe based on groupby基于 groupby 拆分 pandas 数据帧
【发布时间】:2014-07-04 15:53:06
【问题描述】:

我想根据 ZZ 列拆分以下数据框

df = 
        N0_YLDF  ZZ        MAT
    0  6.286333   2  11.669069
    1  6.317000   6  11.669069
    2  6.324889   6  11.516454
    3  6.320667   5  11.516454
    4  6.325556   5  11.516454
    5  6.359000   6  11.516454
    6  6.359000   6  11.516454
    7  6.361111   7  11.516454
    8  6.360778   7  11.516454
    9  6.361111   6  11.516454

作为输出,我想要一个新的DataFrame,其中N0_YLDF 列分成4 个,ZZ 的每个唯一值对应一个新列。我该怎么做?我可以做 groupby,但不知道如何处理分组的对象。

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    将它们存储在dict 中,这样您就可以根据组键访问组数据帧。

    d = dict(tuple(df.groupby('ZZ')))
    d[6]
    
    #    N0_YLDF  ZZ        MAT
    #1  6.317000   6  11.669069
    #2  6.324889   6  11.516454
    #5  6.359000   6  11.516454
    #6  6.359000   6  11.516454
    #9  6.361111   6  11.516454
    

    如果您只需要 DataFrame 的一个子集,在这种情况下只是 'NO_YLDF' 系列,您可以修改 dict 理解。

    d = dict((idx, gp['N0_YLDF']) for idx, gp in df.groupby('ZZ'))
    d[6]
    #1    6.317000
    #2    6.324889
    #5    6.359000
    #6    6.359000
    #9    6.361111
    #Name: N0_YLDF, dtype: float64
    

    【讨论】:

      【解决方案2】:

      还有另一种选择,因为 groupby 返回一个生成器,我们可以简单地使用列表理解来检索第二个值(帧)。

      dfs = [x for _, x in df.groupby('ZZ')]
      

      【讨论】:

        【解决方案3】:

        在 R 中有一个称为 split 的数据帧方法。这适用于所有 R 用户:

        def split(df, group):
             gb = df.groupby(group)
             return [gb.get_group(x) for x in gb.groups]
        

        【讨论】:

        • 你不应该把它全部放在一个系列中吗?以pd.Series(...)结尾
        • 这太棒了。有没有一种简单的方法来获取标识组的键,所以我可以返回一个元组列表,比如[ (key, gb.get_group(x) ) for x in gb.group]
        • 我找到了这个,这很容易:*.com/questions/42513049/…
        • 只是为了提供评论的答案(在链接中有更详细的解释:[(key, gb.get_group(key)) for key in gb.groups]
        • 相同的解决方案,但带有迭代器def split(df, group): gb = df.groupby(group) for g in gb.groups: yield gb.get_group(g)
        【解决方案4】:
        gb = df.groupby('ZZ')    
        [gb.get_group(x) for x in gb.groups]
        

        【讨论】: