(Or a list of lists... I just edited)
Is there an existing python/pandas method for converting a structure like this
food2 = {}
food2["apple"] = ["fruit", "round"]
food2["bananna"] = ["fruit", "yellow", "long"]
food2["carrot"] = ["veg", "orange", "long"]
food2["raddish"] = ["veg", "red"]
into a pivot table like this?
+---------+-------+-----+-------+------+--------+--------+-----+
| | fruit | veg | round | long | yellow | orange | red |
+---------+-------+-----+-------+------+--------+--------+-----+
| apple | 1 | | 1 | | | | |
+---------+-------+-----+-------+------+--------+--------+-----+
| bananna | 1 | | | 1 | 1 | | |
+---------+-------+-----+-------+------+--------+--------+-----+
| carrot | | 1 | | 1 | | 1 | |
+---------+-------+-----+-------+------+--------+--------+-----+
| raddish | | 1 | | | | | 1 |
+---------+-------+-----+-------+------+--------+--------+-----+
Naively, I would probably just loop through the dictionary. I see how I can use a map on each inner list, but I don't know how to join/stack them over the dictionary. Once I did join them, I could just use pandas.pivot_table
for key in food2:
attrlist = food2[key]
onefruit_pairs = map(lambda x: [key, x], attrlist)
one_fruit_frame = pd.DataFrame(onefruit_pairs, columns=['fruit', 'attr'])
print(one_fruit_frame)
fruit attr
0 bananna fruit
1 bananna yellow
2 bananna long
fruit attr
0 carrot veg
1 carrot orange
2 carrot long
fruit attr
0 apple fruit
1 apple round
fruit attr
0 raddish veg
1 raddish red