如何在Python中将Excel数据转换为JSON?

huangapple go评论65阅读模式
英文:

How to convert excel data to json in python?

问题

你可以使用Python中的pandas库来转换数据。以下是一个示例代码,演示如何将给定的数据表转换成所需的JSON格式:

import pandas as pd

# 创建数据表
data = {
    'food ID': [1, 1, 1],
    'name': ['rice', 'soup', 'soup'],
    'ingredients': ['red', 'blue', 'yellow'],
    'ingredient ID': ['R1', 'B1', 'Y1'],
    'amount': [10, 20, 30],
    'unit': ['g', 'g', 'g']
}

df = pd.DataFrame(data)

# 转换为所需的JSON格式
result = {
    'data': []
}

grouped = df.groupby(['food ID', 'name'])
for (food_id, name), group in grouped:
    food_item = {
        'name': name,
        'ingredients': []
    }
    for index, row in group.iterrows():
        ingredient = {
            'name': row['ingredients'],
            'ingredient_id': row['ingredient ID'],
            'amount': row['amount'],
            'unit': row['unit']
        }
        food_item['ingredients'].append(ingredient)
    result['data'].append(food_item)

print(result)

这段代码将输入数据表转换为所需的JSON格式。你不需要使用其他库,只需使用pandas即可完成这项任务。

英文:

My data is below

food ID name ingredients ingredient ID amount unit
1 rice red R1 10 g
1 soup blue B1 20 g
1 soup yellow Y1 30 g

and I want to convert it like this


{
  'data': [
    {
      'name': 'rice',
      'ingredients': [
        {
          'name': 'red',
          'ingredient_id':'R1',
          'amount': 10,
          'unit': 'g',
        }
      ]
    },
    {
      'name': 'soup',
      'ingredients': [
        {
          'name': 'blue',
          'ingredient_id':'B1',
          'amount': 20,
          'unit': 'g',
        },
        {
          'name': 'yellow',
          'ingredient_id':'Y1',
          'amount': 30,
          'unit': 'g',
        }
      ]
    }
  ]
}

How can I do it? Do I need to use the same library as pandas?

答案1

得分: 1

是的,您可以使用Python内部的自定义代码函数来修改数据。

对于您所需的格式,您需要使用以下代码将数据格式化为JSON:

import pandas as pd

data = [[1, 'rice', 'red', 'R1', 10, 'g'],
    [1, 'soup', 'blue', 'B1', 20, 'g'],
    [1, 'soup', 'yellow', 'Y1', 30, 'g'],
    [1, 'apple', 'yellow', 'Y1', 30, 'g']]

df = pd.DataFrame(data, columns=['food ID', 'name', 'ingredients', 'ingredient ID', 'amount', 'unit'])

def convert_data_group(group):
    ingredients = [{'name': row['ingredients'], 'ingredient_id': row['ingredient ID'], 'amount': row['amount'], 'unit': row['unit']} for _, row in group.iterrows()]
    return {'name': group.iloc[0]['name'], 'ingredients': ingredients}

unique_names = df['name'].unique().tolist()
result = []
for name in unique_names:
    group = df[df['name'] == name]
    result.append(convert_data_group(group))

final_result = {'datas': result}
print(final_result)

您的最终结果将是:

{'datas': [{'name': 'rice', 'ingredients': [{'name': 'red', 'ingredient_id': 'R1', 'amount': 10, 'unit': 'g'}]}, {'name': 'soup', 'ingredients': [{'name': 'blue', 'ingredient_id': 'B1', 'amount': 20, 'unit': 'g'}, {'name': 'yellow', 'ingredient_id': 'Y1', 'amount': 30, 'unit': 'g'}]}, {'name': 'apple', 'ingredients': [{'name': 'yellow', 'ingredient_id': 'Y1', 'amount': 30, 'unit': 'g'}]}]}

请注意,我已经去除了代码部分以满足您的要求。

英文:

Yes you can modify your data by using custom code function inside python.

For your required format you need to use this code for format your data into json.

import pandas as pd

data = [[1, 'rice', 'red', 'R1', 10, 'g'],
    [1, 'soup', 'blue', 'B1', 20, 'g'],
    [1, 'soup', 'yellow', 'Y1', 30, 'g'],
    [1, 'apple', 'yellow', 'Y1', 30, 'g']]

df = pd.DataFrame(data, columns=['food ID', 'name', 'ingredients', 'ingredient ID', 'amount', 'unit'])

def convert_data_group(group):
    ingredients = [{'name': row['ingredients'], 'ingredient_id': row['ingredient ID'], 'amount': row['amount'], 'unit': row['unit']} for _, row in group.iterrows()]
    return {'name': group.iloc[0]['name'], 'ingredients': ingredients}

unique_names = df['name'].unique().tolist()
result = []
for name in unique_names:
    group = df[df['name'] == name]
    result.append(convert_data_group(group))

final_result = {'datas': result}
print(final_result)

Your final result will be:

{'datas': [{'name': 'rice', 'ingredients': [{'name': 'red', 'ingredient_id': 'R1', 'amount': 10, 'unit': 'g'}]}, {'name': 'soup', 'ingredients': [{'name': 'blue', 'ingredient_id': 'B1', 'amount': 20, 'unit': 'g'}, {'name': 'yellow', 'ingredient_id': 'Y1', 'amount': 30, 'unit': 'g'}]}, {'name': 'apple', 'ingredients': [{'name': 'yellow', 'ingredient_id': 'Y1', 'amount': 30, 'unit': 'g'}]}]}

如何在Python中将Excel数据转换为JSON?

huangapple
  • 本文由 发表于 2023年2月6日 13:33:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75357649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定