Export itertools permutation to csv

Question:

I tried converting an itertools permutation to a pandas dataframe object but when I export the dataframe i do not get the array generated by permutation

import itertools
import pandas as pd

x = range(69,89)

array = itertools.permutations(x, 4)

for eachpermutation in array:
    print(eachpermutation)

df = pd.DataFrame(eachpermutation) 

df.to_csv("") 

the eachpermutation is fine and printing what I expect but the df produces the following:

    0
0  80
1  79
2  78
3  77
Asked By: topo

||

Answers:

You’ve got two problems:

  1. You passed each_permutation to the DataFrame constructor, which means you only passed it the last permutation generated as the sole source of data. This is almost certainly not what you wanted; it seems fairly clear the DataFrame was intended to be all the permutations. To fix this part, change df = pd.DataFrame(each_permutation) to df = pd.DataFrame(array).

  2. Once that’s fixed, you’ll have another problem: permutations makes an iterator, not a new list or the like. When you iterated over it with your for loop, you consumed all the values in it; trying to iterate it again produces nothing. If you get rid of that loop, the permutations object will be fresh, and the DataFrame will receive the values you expect, rather than nothing.

Answered By: ShadowRanger
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.