在线文字转语音网站:无界智能 aiwjzn.com

Python使用Pandas实现数据读取和写入,包括CSV、Excel、SQL、JSON等

环境准备: 在使用Pandas之前,需要先安装Pandas和相关依赖。可以通过以下命令来安装: python pip install pandas 此外,还需要安装其他依赖的类库,如:xlrd(用于读取Excel文件)、openpyxl(用于写入Excel文件)、pyodbc(用于连接SQL Server数据库)、psycopg2(用于连接PostgreSQL数据库)等。可以通过相应的命令来安装这些类库。 数据集介绍: 下面以一个示例数据集作为样例,该数据集是一个CSV文件,包含了一些学生的基本信息。数据集包含的字段有:姓名、年龄、性别、科目和分数。数据集下载的网址为:https://example.com/example.csv 样例代码如下: python import pandas as pd # 读取CSV文件 df = pd.read_csv('example.csv') # 查看数据集的前5行 print(df.head()) # 将数据集写入Excel文件 df.to_excel('example.xlsx', index=False) # 读取Excel文件 df_excel = pd.read_excel('example.xlsx') # 将数据集写入SQL Server数据库 import pyodbc # 连接数据库 conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=mydb;UID=username;PWD=password') # 创建游标 cursor = conn.cursor() # 创建表格 cursor.execute('CREATE TABLE students (name VARCHAR(255), age INT, gender VARCHAR(255), subject VARCHAR(255), score FLOAT)') # 将数据插入表格 for index, row in df.iterrows(): cursor.execute('INSERT INTO students (name, age, gender, subject, score) VALUES (?, ?, ?, ?, ?)', row['name'], row['age'], row['gender'], row['subject'], row['score']) # 提交事务 conn.commit() # 关闭数据库连接 conn.close() # 读取SQL Server数据 conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=mydb;UID=username;PWD=password') df_sql = pd.read_sql('SELECT * FROM students', conn) # 将数据集写入JSON文件 df.to_json('example.json', orient='records') # 读取JSON文件 df_json = pd.read_json('example.json') 以上是使用Pandas实现数据读取和写入的示例代码,代码中演示了如何读取CSV文件、写入Excel文件、写入SQL Server数据库、读取SQL Server数据、写入JSON文件和读取JSON文件。请注意根据实际情况修改数据库连接信息和文件路径。