使用 Pandas 将 Excel 表格列数据转换为 JSON 格式

本教程将演示如何使用 Python Pandas 库从 Excel 表格中读取一列数据,将其转换为字符串类型,并将其存储到 JSON 文件中。

代码实现:

import pandas as pd
import json

# 读取excel表格数据
df = pd.read_excel('example.xlsx')

# 提取需要的一列数据并转化为字符串类型
column_data = df['Column_Name'].astype(str)

# 将数据存入json文件
data_dict = {'column_data': column_data.tolist()}
with open('data.json', 'w') as json_file:
    json.dump(data_dict, json_file)

解释:

  1. 导入库: 首先,导入 pandasjson 库。
  2. 读取 Excel 表格: 使用 pd.read_excel() 函数读取 Excel 表格。
  3. 提取列数据: 使用 df['Column_Name'] 获取指定列的数据,并使用 astype(str) 将其转换为字符串类型。
  4. 创建字典: 创建一个字典,将列数据存储在名为 column_data 的键下。
  5. 写入 JSON 文件: 使用 json.dump() 函数将字典写入名为 data.json 的 JSON 文件中。

注意:

  • 请将代码中的 example.xlsx 替换为你的 Excel 文件路径。
  • 请将 Column_Name 替换为你想读取的列名。
  • 运行代码后,你将在当前目录下生成一个名为 data.json 的 JSON 文件。

示例:

假设你的 Excel 表格名为 data.xlsx,包含一列名为 Age 的数据。执行上述代码后,你将得到一个名为 data.json 的 JSON 文件,内容如下:

{
  "column_data": [
    "25",
    "30",
    "28",
    "32"
  ]
}

本教程展示了如何使用 Pandas 库将 Excel 表格中的列数据转换为 JSON 格式。你可以根据自己的需求修改代码,例如添加多个列数据到 JSON 文件中。

Python Pandas 将 Excel 表格列数据转换为 JSON 格式

原文地址: https://www.cveoy.top/t/topic/pc8I 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录