由于您是按年龄分组,因此让我们返回每个组的所有排列,然后求乘积(使用 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
在这样做之前...你may能够做一些稍微低级的事情):
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,))]
我们可以用 sum 将它们粘合起来:
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']]
注:它may更快地使用numpy 置换矩阵 https://stackoverflow.com/q/27323448/1240268 and pd.tools.util.cartesian_product
。我怀疑这是一个很大的问题,并且不会对此进行探索,除非速度慢得无法使用(无论如何它都可能会很慢,因为可能有很多排列)......