繁体   English   中英

从列表列表创建数据框

[英]Create a Dataframe from list of lists

我有两个列表,如下所示

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']]

quan_listingre_list的长度相同。 两个列表的每个内部列表的长度相同。 例如quan_list[0]具有尺寸为的相同ingre_list[0] 我想从这些列表中创建一个数据ingre_list ,标题是来自ingre_list的项目,并且每个项目都应该在标题中出现一次。 然后每一行应该包含来自quan_list的成分的quan_list 要创建空数据框,我使用了以下代码:

unique_ingre= set(x for l in ingre_list for x in l)
df1 = pd.DataFrame(columns=unique_ingre)

现在我无法在每一行中插入数量。

示例数据框考虑值ingre_list[0]quan_list[0]

bread egg chicken   sugar      dressing ..... water    garlic
           2 lbs   1/3 cup                    1/2 cup      2

如果有人可以帮助我,我真的很感激。 只是为了让您知道 quan_list 和 ingre_list 的长度可以增加。 如果这个东西可以用python写成一个csv文件也很好。

你可以试试,注意我添加groupbyhead因为你的ingre_list在每个子列表中有重复的项目,如果在实际数据中没有重复项,你可以删除.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM