Reputation: 300
I have two list of lists which looks like the following
ingre_list = [['chicken',
'oil',
'garlic',
'pepper',
'juice',
'sugar',
'ketchup',
'vinegar',
'water',
'sauce'],
['butter', 'sugar', 'eggs', 'bananas', 'salt'],
['pork',
'beef',
'egg',
'cheese',
'bread',
'garlic',
'salt',
'pepper',
'milk',
'parsley'],
['beef',
'bread',
'egg',
'onions',
'salt',
'pepper',
'ketchup',
'milk',
'vinegar',
'sugar',
'ketchup'],
['salt', 'sugar', 'butter'],
['sausage',
'garlic',
'tomatoes',
'sauce',
'water',
'basil',
'parsley',
'sugar',
'salt',
'pepper',
'pepper',
'spaghetti',
'cheese'],
['bananas',
'juice',
'salt',
'butter',
'sugar',
'eggs',
'butter',
'cheese',
'cream',
'sugar'],
['beef', 'gravy', 'dressing', 'dressing', 'water'],
['salt', 'butter', 'sugar', 'sugar', 'eggs', 'oats', 'raisins']]
quan_list= [['2 lbs',
'2',
'2',
'3/4 teaspoon',
'1/4 cup',
'1/3 cup',
'2 tablespoons',
'1 tablespoon',
'1/2 cup',
'1/3 cup'],
['1/2 cup', '1 cup', '1', '1', '1/2 teaspoon'],
['1/2',
'1/2',
'1/2',
'1/2 cup',
'1/3 cup',
'1/3',
'1/3',
'1 teaspoon',
'1/3 cup',
'1/4 cup'],
['1/4',
'1/4',
'1/4',
'1/4',
'1 teaspoon',
'1/4 teaspoon',
'4 tablespoons',
'1/2-2/3 cup',
'4 tablespoons',
'4',
'1/2 cup'],
['1 teaspoon', '1/4 cup', '1/2 cup'],
['2 lbs',
'2',
'2',
'2',
'2 cups',
'3 teaspoons',
'2 teaspoons',
'2',
'1 teaspoon',
'1/4-1/2 teaspoon',
'1/4 teaspoon',
'1/4',
'1/4'],
['1/4',
'2 teaspoons',
'1/4 teaspoon',
'3/4 cup',
'3/4',
'3/4',
'1/2 cup',
'1/2',
'1/2',
'1/2'],
['1/2', '1/2', '1/2', '1/2', '1/2 cup'],
['1 teaspoon', '1 cup', '1 cup', '1 cup', '1', '3 cups', '3']]
The quan_list
and ingre_list
are of same length. Each inner list of both the lists are of same length. For example quan_list[0]
has the same size as that of ingre_list[0]
. I want to create a dataframe from these lists with the headers be the items from the ingre_list
and each item should appear once in the header. Then each row should contain the quantity of the ingredient from the quan_list
.
To create the empty dataframe I have used the following code:
unique_ingre= set(x for l in ingre_list for x in l)
df1 = pd.DataFrame(columns=unique_ingre)
Now I am having trouble to insert the quantities in each row.
Example Dataframe consider the values ingre_list[0]
and quan_list[0]
bread egg chicken sugar dressing ..... water garlic
2 lbs 1/3 cup 1/2 cup 2
IF anyone can please help me its really appreciated. Just to let you know that length of quan_list and ingre_list can increase. Its also fine if this thing can be written in a csv file in python.
Upvotes: 1
Views: 81
Reputation: 323376
You can try , notice I am adding groupby
and head
due to your ingre_list
have duplicated item within each sub-list, if in real data there is no duplicates , you can remove .groupby(level=0).head(1)
s=pd.concat([pd.Series(y, index=x).groupby(level=0).head(1) for x , y in zip(ingre_list , quan_list)],axis=1).T
Upvotes: 2