查找保留排序的 Pandas DataFrame 的所有排列的快速方法?

Rea*_*son 5 python sorting permutation pandas

我有一个 DataFrame,我想找到它的所有排列,以在其中一列上实现简单的升序排序。(有很多关系。)例如,在下面的DataFrame中

df = pd.DataFrame({'name': ["Abe", "Bob", "Chris", "David", "Evan"], 
                   'age': [28, 20, 21, 22, 21]})
Run Code Online (Sandbox Code Playgroud)

我希望按年龄排序并获取订单["Bob", "Chris", "Evan", "David", "Abe"]["Bob", "Evan", "Chris", "David", "Abe"].

我是python(和pandas)的新手,并且很好奇是否有一种我没有看到的简单方法来做到这一点。

谢谢!

And*_*den 4

由于您是按年龄分组,因此让我们返回每个组的所有排列,然后求乘积(使用 itertools 的乘积和排列函数):

In [11]: age = df.groupby("age")
Run Code Online (Sandbox Code Playgroud)

如果我们看一下单个组的排列:

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]
Run Code Online (Sandbox Code Playgroud)

我们可以通过仅返回每个组的索引来在整个 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,))]
Run Code Online (Sandbox Code Playgroud)

我们可以用 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)]
Run Code Online (Sandbox Code Playgroud)

如果你将这些作为一个列表,你可以应用 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]
Run Code Online (Sandbox Code Playgroud)

以及名称列(列表):

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']]
Run Code Online (Sandbox Code Playgroud)

注意:使用numpy 置换矩阵可能会更快。我怀疑这是一个很大的问题,并且不会对此进行探索,除非速度慢得无法使用(无论如何它都可能会很慢,因为可能有很多排列)......pd.tools.util.cartesian_product