Python Pandas 将 Excel 列数据转换为数组并存入 JSON 文件
Python Pandas 将 Excel 列数据转换为数组并存入 JSON 文件
本文将详细介绍如何使用 Python Pandas 库读取 Excel 文件中的一列数据,将其转换为数组类型,并将其存储到 JSON 文件中。
代码实现
import pandas as pd
import json
# 读取 Excel 文件
df = pd.read_excel('path_to_excel_file.xlsx')
# 读取一列数据
column_data = df['column_name'].tolist() # 将该列数据转化为数组类型
# 存储数据到 JSON 文件中
data = {'column_data': column_data}
with open('data.json', 'w') as file:
json.dump(data, file)
说明:
- 请将代码中的
'path_to_excel_file.xlsx'替换为你的 Excel 文件的路径。 - 将
'column_name'替换为你要读取的列的名称。 - 执行代码后,数据将存储在名为
data.json的 JSON 文件中。
代码解释
- 导入库: 首先导入
pandas和json库,分别用于处理 Excel 数据和创建 JSON 文件。 - 读取 Excel 文件: 使用
pd.read_excel()函数读取 Excel 文件,并将数据存储到df数据框中。 - 读取一列数据: 使用
df['column_name'].tolist()获取指定列的数据并将其转换为数组类型。 - 存储数据到 JSON 文件: 使用
json.dump()函数将数据写入 JSON 文件。
示例
假设你的 Excel 文件名为 example.xlsx,要读取的列名为 numbers,则代码如下:
import pandas as pd
import json
# 读取 Excel 文件
df = pd.read_excel('example.xlsx')
# 读取一列数据
column_data = df['numbers'].tolist()
# 存储数据到 JSON 文件中
data = {'numbers': column_data}
with open('data.json', 'w') as file:
json.dump(data, file)
执行完代码后,你将在当前目录下找到名为 data.json 的 JSON 文件,其中包含 numbers 列的所有数据。
原文地址: https://www.cveoy.top/t/topic/pc7s 著作权归作者所有。请勿转载和采集!