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
Answers:
You’ve got two problems:
-
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)
.
-
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.
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
You’ve got two problems:
-
You passed
each_permutation
to theDataFrame
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 theDataFrame
was intended to be all the permutations. To fix this part, changedf = pd.DataFrame(each_permutation)
todf = pd.DataFrame(array)
. -
Once that’s fixed, you’ll have another problem:
permutations
makes an iterator, not a newlist
or the like. When you iterated over it with yourfor
loop, you consumed all the values in it; trying to iterate it again produces nothing. If you get rid of that loop, thepermutations
object will be fresh, and theDataFrame
will receive the values you expect, rather than nothing.