Python:迭代每个DataFrame组的最快方法

问题描述 投票:0回答:3

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

问题是每列中的唯一元素的数量是不同的,这意味着,以下面的数据帧为例,我需要一个尝试,除了语句,因为对于例如a1,b2,c2的某些分组,G不存在,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
3个回答
0
投票

你可以循环遍历组

for name, frame in df.groupby(...):

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


0
投票

您应该根据实际可用的内容过滤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):
    # ...

0
投票

只是它的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)
© www.soinside.com 2019 - 2024. All rights reserved.