数据导入导出(CSV, Excel, JSON)
在数据分析中,导入和导出数据是常见的操作。Python 提供了多种工具来处理常见的数据格式,如 CSV、Excel 和 JSON。以下是如何使用 Python 进行这些数据格式的导入和导出操作。
1. 导入导出 CSV 文件
CSV(Comma-Separated Values)是一种常见的文本数据格式,用于存储表格数据。Python 的 pandas 库提供了非常方便的函数来读取和写入 CSV 文件。
1.1 读取 CSV 文件
python
import pandas as pd
# 读取 CSV 文件
df = pd.read_csv('data.csv')
print(df.head())1.2 写入 CSV 文件
python
# 写入 CSV 文件
df.to_csv('output.csv', index=False) # index=False 表示不写入行索引2. 导入导出 Excel 文件
Excel 是一种常见的电子表格格式,Python 通过 pandas 和 openpyxl 库支持读取和写入 Excel 文件。
2.1 读取 Excel 文件
python
# 读取 Excel 文件
df = pd.read_excel('data.xlsx', sheet_name='Sheet1') # sheet_name 可以是工作表名称或索引
print(df.head())2.2 写入 Excel 文件
python
# 写入 Excel 文件
df.to_excel('output.xlsx', sheet_name='Sheet1', index=False)3. 导入导出 JSON 文件
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,适合存储结构化数据。Python 的 json 模块可以方便地处理 JSON 数据。
3.1 读取 JSON 文件
python
import json
# 读取 JSON 文件
with open('data.json', 'r') as file:
data = json.load(file)
print(data)3.2 写入 JSON 文件
python
# 写入 JSON 文件
data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
with open('output.json', 'w') as file:
json.dump(data, file, indent=4) # indent=4 美化 JSON 格式4. 结合 Pandas 和 JSON
Pandas 支持将数据框转换为 JSON 格式,并从 JSON 文件中读取数据。
4.1 从 Pandas DataFrame 导出 JSON
python
# 将 DataFrame 导出为 JSON 格式
df.to_json('output.json', orient='records', lines=True)orient='records':每行是一个 JSON 对象。lines=True:每个记录占据一行。
4.2 从 JSON 导入到 Pandas DataFrame
python
# 从 JSON 文件读取数据
df = pd.read_json('data.json')
print(df.head())5. 总结
- CSV 文件:使用
pandas库中的read_csv和to_csv方法进行导入导出操作。 - Excel 文件:使用
pandas库中的read_excel和to_excel方法进行导入导出操作。需安装openpyxl库支持 Excel 操作。 - JSON 文件:使用 Python 内置的
json模块进行导入导出操作,也可以使用pandas处理 JSON 数据。
这些方法可以帮助你高效地管理数据的导入和导出工作。