由于您按年龄分组,让我们这样做并返回每个组的所有排列,然后获取产品(使用itertools的产品和排列函数):
In [11]: age = df.groupby("age")
如果我们看一个组的排列:
In [12]: age.get_group(21)
Out[12]:
age name
2 21 Chris
4 21 Evan
In [13]: list(permutations(age.get_group(21).index))
Out[13]: [(2, 4), (4, 2)]
In [14]: [df.loc[list(p)] for p in permutations(age.get_group(21).index)]
Out[14]:
[ age name
2 21 Chris
4 21 Evan, age name
4 21 Evan
2 21 Chris]
我们可以通过返回每个组的索引来对整个DataFrame执行此操作(假设索引是唯一的,如果在执行此操作之前它不是reset_index …您可能能够执行稍微更低级别的操作):
In [21]: [list(permutations(grp.index)) for (name, grp) in age]
Out[21]: [[(1,)], [(2, 4), (4, 2)], [(3,)], [(0,)]]
In [22]: list(product(*[(permutations(grp.index)) for (name, grp) in age]))
Out[22]: [((1,), (2, 4), (3,), (0,)), ((1,), (4, 2), (3,), (0,))]
我们可以将这些加起来:
In [23]: [sum(tups, ()) for tups in product(*[(permutations(grp.index)) for (name, grp) in age])]
Out[23]: [(1, 2, 4, 3, 0), (1, 4, 2, 3, 0)]
如果你把它们作为一个列表,你可以应用loc(它可以获得你想要的结果):
In [24]: [df.loc[list(sum(tups, ()))] for tups in product(*[list(permutations(grp.index)) for (name, grp) in age])]
Out[24]:
[ age name
1 20 Bob
2 21 Chris
4 21 Evan
3 22 David
0 28 Abe, age name
1 20 Bob
4 21 Evan
2 21 Chris
3 22 David
0 28 Abe]
和列表的列表:
In [25]: [list(df.loc[list(sum(tups, ())), "name"]) for tups in product(*[(permutations(grp.index)) for (name, grp) in age])]
Out[25]:
[['Bob', 'Chris', 'Evan', 'David', 'Abe'],
['Bob', 'Evan', 'Chris', 'David', 'Abe']]
注意:使用numpy permutation matrix和pd.tools.util.cartesian_product可能会更快.我怀疑这很多,并且不会探索这个,除非这个速度非常缓慢(无论如何它可能会很慢,因为可能会有很多排列)…