我有一个数据帧,可以分成多个组,执行功能,然后将组重新组合为一个数据帧。
问题是每列中的唯一元素的数量是不同的,这意味着,以下面的数据帧为例,我需要一个尝试,除了语句,因为对于例如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....
你可以循环遍历组
for name, frame in df.groupby(...):
name
应该是小组,frame
应该是df.groupby(...).get_group(...)
的输出
您应该根据实际可用的内容过滤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):
# ...
只是它的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)