使用 pandas 对数据帧的多行进行排列

发布于 2025-01-13 04:49:15 字数 349 浏览 4 评论 0原文

我有一个这样的数据框:

d = pd.DataFrame({'Job': ['A', 'B', 'C', 'D', 'E'],
        'Machine1': [1,3,2,4,3], 'Machine2': [2,0,5,1,2]})

对于索引'Job',我需要找到长度为5的所有排列,基本上是(5个阶乘)排列。索引的长度可能会因不同的场景而改变,所以我并不是在寻找仅特定于 5 个作业的代码。

预期输出:A、B、C、D、E; A、C、D、E、B; E,D,C,B,A ...等等多达120种这样的方式。在基础数学中,它是表示为 5P5 的排列

I have a data frame of this kind:

d = pd.DataFrame({'Job': ['A', 'B', 'C', 'D', 'E'],
        'Machine1': [1,3,2,4,3], 'Machine2': [2,0,5,1,2]})

For the index 'Job', I need to find all permutations of length 5, basically (5 factorial) permutations. The length of the index may change for a different scenario, so I am not looking for a code specific to 5 jobs only.

Expected output: A,B,C,D,E; A,C,D,E,B; E,D,C,B,A ... and so on up to 120 such ways. In basic math, it is a permutation expressed as 5P5

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

注定孤独终老 2025-01-20 04:49:15

我认为您正在寻找内置函数 itertools .permutations()

import itertools as it
permutations = list(it.permutations(d['Job']))

输出:

>>> permutations
[('A', 'B', 'C', 'D', 'E'),
 ('A', 'B', 'C', 'E', 'D'),
 ('A', 'B', 'D', 'C', 'E'),
 ('A', 'B', 'D', 'E', 'C'),
 ('A', 'B', 'E', 'C', 'D'),
...

>>> len(permutations)
120

I think you're looking for the built-in function itertools.permutations():

import itertools as it
permutations = list(it.permutations(d['Job']))

Output:

>>> permutations
[('A', 'B', 'C', 'D', 'E'),
 ('A', 'B', 'C', 'E', 'D'),
 ('A', 'B', 'D', 'C', 'E'),
 ('A', 'B', 'D', 'E', 'C'),
 ('A', 'B', 'E', 'C', 'D'),
...

>>> len(permutations)
120
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文