#导入pandas
import pandas as pd
import numpy as np #导入SqlAlchemy
from sqlalchemy import create_engine if __name__ == "__main__":
#建立数据库引擎
engine = create_engine('mysql+pymysql://root:mysql@localhost:3306/mymac')
#写一条sql
sql = 'select id,name,age,gender from student'
#建立dataframe
df = pd.read_sql_query(sql,engine)
# print(df)
#按照年龄倒序 正序:ascending=True
#翻译为sql select * from student order by asc | desc
# df = df.sort_values(['age','gender'],ascending=False)
# print(df) #取年龄最小的学生 在尾部取值
#翻译为sql select * from student order by age limit 1
# df = df.sort_values(['age']).tail(1)
# print(df) #求整个班的平均年龄
avg_age= df.age.mean()
#使用loc方法指定字段
print(df.loc[(df['age']<avg_age ) & df['gender']==1]) #获取指定字段
# print(df.loc[df['gender']==1,['id','name']]) #将dataframe写入数据表,表名,数据引擎,索引是否入库
# df.to_sql('student_copy',engine,index=False) #前提要安装好 openpyxl 安装命令 pip install openpyxl
#导入成excel文件
# df.to_excel('student.xlsx') # print(Student.objects.all())