啤酒研究的嵌套词典

nested dictionaries to beer study

提问人:XxEglyxX 提问时间:11/11/2023 最后编辑:ndc85430XxEglyxX 更新时间:11/12/2023 访问量:37

问:

我有一个带有“成分”列的数据帧,其中包含嵌套的字典。我需要将每种成分及其数量提取到独立的色谱柱中,但我不知道该怎么做。有人可以帮我吗? 我只想每列有一个值,以便以后将其导入 Tableau 并避免任何问题

{'malt': [{'name': 'Maris Otter Extra Pale',
   'amount': {'value': 3.3, 'unit': 'kilograms'}},
  {'name': 'Caramalt', 'amount': {'value': 0.2, 'unit': 'kilograms'}},
  {'name': 'Munich', 'amount': {'value': 0.4, 'unit': 'kilograms'}}],
 'hops': [{'name': 'Fuggles',
   'amount': {'value': 25, 'unit': 'grams'},
   'add': 'start',
   'attribute': 'bitter'},
  {'name': 'First Gold',
   'amount': {'value': 25, 'unit': 'grams'},
   'add': 'start',
   'attribute': 'bitter'},
  {'name': 'Fuggles',
   'amount': {'value': 37.5, 'unit': 'grams'},
   'add': 'middle',
   'attribute': 'flavour'},
  {'name': 'First Gold',
   'amount': {'value': 37.5, 'unit': 'grams'},
   'add': 'middle',
   'attribute': 'flavour'},
  {'name': 'Cascade',
   'amount': {'value': 37.5, 'unit': 'grams'},
   'add': 'end',
   'attribute': 'flavour'}],
 'yeast': 'Wyeast 1056 - American Ale™'}

如果有人对如何重新组织数据有更好的想法,请告诉我

def extract_values(row):
    return {
        'malt_name': row['ingredients'].get('malt', [{}])[0].get('name', None),
        'malt_amount_value': row['ingredients'].get('malt', [{}])[0].get('amount', {}).get('value', None),
        'hops_name': row['ingredients'].get('hops', [{}])[0].get('name', None),
        'hops_amount_value': row['ingredients'].get('hops', [{}])[0].get('amount', {}).get('value', None),
        'yeast': row['ingredients'].get('yeast', None)
    }


new_columns = df.apply(extract_values, axis=1, result_type='expand')


df = pd.concat([df, new_columns], axis=1)
Python Pandas 数据帧 字典

评论


答: 暂无答案