Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dataframe from all possible combinations of values of given categories

I have

{"A":[0,1], "B":[4,5], "C":[0,1], "D":[0,1]}

what I want it

A   B   C   D
0   4   0   0
0   4   0   1
0   4   1   0
0   4   1   1
1   4   0   1

...and so on. Basically all the combinations of values for each of the categories. What would be the best way to achieve this?

like image 675
y2p Avatar asked Jan 10 '23 15:01

y2p


1 Answers

If x is your dict:

>>> pandas.DataFrame(list(itertools.product(*x.values())), columns=x.keys())
    A  C  B  D
0   0  0  4  0
1   0  0  4  1
2   0  0  5  0
3   0  0  5  1
4   0  1  4  0
5   0  1  4  1
6   0  1  5  0
7   0  1  5  1
8   1  0  4  0
9   1  0  4  1
10  1  0  5  0
11  1  0  5  1
12  1  1  4  0
13  1  1  4  1
14  1  1  5  0
15  1  1  5  1

If you want the columns in a particular order you'll need to switch them afterwards (with, e.g., df[["A", "B", "C", "D"]].

like image 177
BrenBarn Avatar answered Jan 17 '23 15:01

BrenBarn