【问题标题】:How to get every possible permutation from a list of numbers and store in a dataframe?如何从数字列表中获取所有可能的排列并存储在数据框中?
【发布时间】:2018-12-21 01:32:17
【问题描述】:

我有一个数字列表,1-6,我需要所有可能的排列,并且需要存储在数据框中。但我还需要数据框将列命名为“Month 1”、“Month 2”、“Month 3”等。

所以我想要这样的东西:

Month 1  Month 2  Month 3  Month 4  Month 5  Month 6
1        2        3        4        5        6
1        2        3        4        6        5
1        2        3        5        4        6
1        2        3        5        6        4

etc.

我需要存储所有 720 个可能的排列。

我该怎么做?我尝试过使用itertools.permutation,但遇到了问题。

【问题讨论】:

  • 显示您的尝试,然后我们将帮助您修复错误。我们不会为你写的。

标签: python permutation itertools


【解决方案1】:
from itertools import permutations
import pandas as pd
h = ['month-{}'.format(i) for i in range(1,7)]
b = [list(i) for i in permutations([i for i in range(1, 7)])]
pd.DataFrame(b, columns=h)

#output 
Out[12]:
     month-1  month-2  month-3  month-4  month-5  month-6
0          1        2        3        4        5        6
1          1        2        3        4        6        5
2          1        2        3        5        4        6
3          1        2        3        5        6        4
4          1        2        3        6        4        5
5          1        2        3        6        5        4
6          1        2        4        3        5        6

【讨论】:

  • 请不要回答不努力的问题。
  • @Barmar 虽然我同意你的观点,santokiya 应该通过发布他的尝试来表现出更多的努力,但我认为你不应该阻止那些希望尝试并给出答案的人。
  • @ycx 如果我们不阻止回答不好的问题,我们就会鼓励提出不好的问题。他需要了解哪些问题值得回答。
  • @Barmar santokiya 显然是一个新用户。新用户不会以这种方式学到任何东西 imo
  • @ycx 我说的是 mamun 学习要回答什么样的问题。
【解决方案2】:

使用itertools.permutations 可以做到这一点:

import pandas as pd
import itertools

a = itertools.permutations([1,2,3,4,5,6])

df = pd.DataFrame(list(a), columns=['Month' + str(i) for i in range(1,7)])

会产生:

Month1  Month2  Month3  Month4  Month5  Month6
0   1   2   3   4   5   6
1   1   2   3   4   6   5
2   1   2   3   5   4   6
3   1   2   3   5   6   4

【讨论】:

    【解决方案3】:

    我不确定从排列中获取数据框有什么问题。这是我的例子。

    from itertools import permutations
    a= np.arange(6)
    df= pd.DataFrame([comb for comb in permutations(a)],
                     columns=['Month 1','Month 2' ,'Month 3','Month 4','Month 5','Month 6'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2021-04-18
      相关资源
      最近更新 更多