python将excel导入mysql,调整数据类型
时间: 2023-07-07 08:33:42 浏览: 150
在将Excel导入MySQL时,可以使用pandas的`to_sql`方法将数据导入MySQL,同时也可以使用pandas的`astype`方法调整数据类型。
以下是一个示例代码,假设有一个Excel文件"students.xlsx",需要将其导入到MySQL的"students"表中,并调整其中的"age"列为整型。
```python
import pandas as pd
import MySQLdb
# MySQL数据库连接信息
host = 'localhost'
port = 3306
user = 'root'
passwd = 'password'
db = 'test'
# 连接MySQL数据库
conn = MySQLdb.connect(host=host, port=port, user=user, passwd=passwd, db=db)
# 读取学生信息Excel文件
df_students = pd.read_excel('students.xlsx')
# 调整age列的数据类型为整型
df_students['age'] = df_students['age'].astype('int')
# 将学生信息插入到MySQL的students表中
df_students.to_sql('students', conn, if_exists='replace', index=False)
# 关闭MySQL数据库连接
conn.close()
```
在以上示例代码中,`astype`方法用于将"age"列的数据类型调整为整型。如果有多个列需要调整,可以使用`astype`方法的字典参数来指定列名和对应的数据类型。例如:
```python
df_students = pd.read_excel('students.xlsx')
df_students = df_students.astype({'age': 'int', 'score': 'float'})
```
以上代码将"age"列的数据类型调整为整型,"score"列的数据类型调整为浮点型。
阅读全文
相关推荐















