我有一个 DataFrame,我想找到其中一列满足简单升序排序的所有排列。 (有很多关系。)例如,在下面的DataFrame中
df = pd.DataFrame({'name': ["Abe", "Bob", "Chris", "David", "Evan"],
'age': [28, 20, 21, 22, 21]})
我希望按年龄排序并获得订单 ["Bob", "Chris", "Evan", "David", "Abe"]
和 ["Bob”、“Evan”、“Chris”、“David”、“Abe”]
。
我是 python(和 pandas)的新手,很好奇是否有一种我看不到的简单方法可以做到这一点。
谢谢!
最佳答案
由于您是按年龄分组的,所以让我们这样做并返回每个组的所有排列,然后获取乘积(使用 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
。我怀疑它太多了,除非它非常慢(它可能会很慢,因为可能有很多排列),否则不会探索它......
关于python - 快速找到保留排序的 pandas DataFrame 的所有排列的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29992105/