如何从数字列表中获取所有可能的排列并存储在数据框中?

时间:2018-12-21 01:32:18

标签: python permutation itertools

我有一个1-6的数字列表,需要所有可能的排列,并且需要存储在数据框中。但是我还需要数据框具有名为“第1个月”,“第2个月”,“第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,但遇到了麻烦。

3 个答案:

答案 0 :(得分:3)

opt

答案 1 :(得分:1)

使用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

答案 2 :(得分:0)

我不确定从排列中获取数据框会遇到什么麻烦。这是我的例子。

{
"html_attributions" : [],
"results" : [
  {
     "geometry" : {
        "location" : {
           "lat" : -33.870775,
           "lng" : 151.199025
        }
     },
     "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/travel_agent-71.png",
     "id" : "21a0b251c9b8392186142c798263e289fe45b4aa",
     "name" : "Rhythmboat Cruises",
     "opening_hours" : {
        "open_now" : true
     },
     "photos" : [
        {
           "height" : 270,
           "html_attributions" : [],
           "photo_reference" : "CnRnAAAAF-LjFR1ZV93eawe1cU_3QNMCNmaGkowY7CnOf-kcNmPhNnPEG9W979jOuJJ1sGr75rhD5hqKzjD8vbMbSsRnq_Ni3ZIGfY6hKWmsOf3qHKJInkm4h55lzvLAXJVc-Rr4kI9O1tmIblblUpg2oqoq8RIQRMQJhFsTr5s9haxQ07EQHxoUO0ICubVFGYfJiMUPor1GnIWb5i8",
           "width" : 519
        }
     ],
     "place_id" : "ChIJyWEHuEmuEmsRm9hTkapTCrk",
     "scope" : "GOOGLE",
     "alt_ids" : [
        {
           "place_id" : "D9iJyWEHuEmuEmsRm9hTkapTCrk",
           "scope" : "APP"
        }
     ],
     "reference" : "CoQBdQAAAFSiijw5-cAV68xdf2O18pKIZ0seJh03u9h9wk_lEdG-cP1dWvp_QGS4SNCBMk_fB06YRsfMrNkINtPez22p5lRIlj5ty_HmcNwcl6GZXbD2RdXsVfLYlQwnZQcnu7ihkjZp_2gk1-fWXql3GQ8-1BEGwgCxG-eaSnIJIBPuIpihEhAY1WYdxPvOWsPnb2-nGb6QGhTipN0lgaLpQTnkcMeAIEvCsSa0Ww",
     "types" : [ "travel_agency", "restaurant", "food", "establishment" ],
     "vicinity" : "Pyrmont Bay Wharf Darling Dr, Sydney"
   }
  ],
 "status" : "OK"
}