【问题标题】:Python: Quickest way of iterating through each DataFrame groupPython:迭代每个 DataFrame 组的最快方法
【发布时间】:2018-02-26 03:57:32
【问题描述】:

我有一个数据框,它可以分成多个组,执行功能,然后将这些组重新组合成一个数据框。

问题是每列中唯一元素的数量是不同的,也就是说,以下面的数据框为例,我需要尝试一下,除了声明,因为 G 对于 Eg a1 的某些分组不存在, b2,c2,d1 不存在。

除了语句之外,无需尝试即可遍历所有这些组的最快方法是什么?

A  B   C  D
a1 b1 c1 d1
a1 b2 c2 d1
a2 b3 c3 d1
a2 b4 c4 d1

As = df.A.unique()
Bs = df.B.unique()
Cs = df.C.unique()
Ds = df.D.unique()

 for a, b, c, d in itertools.product(As, Bs, Cs, Ds):
     G = df.groupby(['A', 'B', 'C', 'D']).get_group((a,b,c,d))
     Some more code below....

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    你可以循环遍历像

    这样的组
    for name, frame in df.groupby(...):
    

    name 应该是组,frame 应该是df.groupby(...).get_group(...) 的输出

    【讨论】:

      【解决方案2】:

      您应该根据实际可用的内容过滤您的 a,b,c,d 元组:

      possible = set(itertools.product(As, Bs, Cs, Ds))
      available = set(tuple(x) for x in df[['A', 'B', 'C', 'D']].unique())
      
      for a, b, c, d in (possible & available):
          # ...
      

      【讨论】:

        【解决方案3】:

        只需迭代groupby 对象:

        import pandas as pd
        
        df = pd.DataFrame({"A":["a", "a", "b", "b", "a"], "B":[1, 2, 1, 2, 2]})
        
        for key, g in df.groupby(["A", "B"]):
            print(key)
            print(g)
        

        【讨论】:

          猜你喜欢
          • 2019-04-10
          • 2017-11-28
          • 2022-06-13
          • 1970-01-01
          • 1970-01-01
          • 2019-04-08
          • 2023-04-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多