Pandas

From ElectroDragon Wiki
Revision as of 23:27, 2 May 2020 by Chao (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

apt-get install python-pandas

dependencies: numpy, versioneer

  • pip install pandas==0.24.2


Pandas MYSQL

# -*- coding: utf-8 -*-
# 导入必要模块
import pandas as pd
from sqlalchemy import create_engine
# 初始化数据库连接,使用pymysql模块
# MySQL的用户:root, 密码:147369, 端口:3306,数据库:mydb
engine = create_engine('mysql+pymysql://root:147369@localhost:3306/mydb')
# 查询语句,选出employee表中的所有数据
sql = 
     select * from employee;
     
# read_sql_query的两个参数: sql语句, 数据库连接
df = pd.read_sql_query(sql, engine)
# 输出employee表的查询结果
print(df)
# 新建pandas中的DataFrame, 只有id,num两列
df = pd.DataFrame({'id':[1,2,3,4],'num':[12,34,56,89]})
# 将新建的DataFrame储存为MySQL中的数据表,不储存index列
df.to_sql('mydf', engine, index= False)
print('Read from and write to Mysql table successfully!')

Pandas HTML

  • df.to_html