Pandas可以读取与存取像CSV\EXCEL\JSON\HTML\SQL数据库等格式的资料,具体如下:
一:从excel中读取数据并另存一张表
#读取excel中的数据
bill=pd.read_excel('./data1.xls')
print(type(bill))
print(bill.head(10))
#引入os模块,包含多个标准函数
import os
#如果指定路径不存在相应文件,则创建文件
if not os.path.exists('./data1.xls'):
bill.to_excel('./data1.xls')
if not os.path.exists('./data2.xls'):
bill.to_excel('.data2.xls',sheet_name='user_name',index=False) #index设置为false,则生成的数据中就没有行索引编号了
输出:
例②:将DataFrame导出为其他格式(json\html\dict等)的文件
#将DataFrame导出为其他格式(json\html\dict等)的数据
bill=pd.read_excel('.//\.data2.xls')
print(bill.head(10).to_dict(),'\n')
print(bill.head(10).to_html(),'\n')
print(bill.head(10).to_json())
bill.to_json('./bill_to_json.json')
输出:
二、从数据库中导入数据
例:
#pymysql是一个Python语言的扩展库,用于在Python运行环境下使用SQL数据库。
#安装pymysql:pip install pymysql
import pymysql
con=pymysql.connect(host='localhost',port=3333,user='root',passwd='root',db='dgact3')
sql='select * from ucr_act3.tf_f_user'
df=pd.read_sql(sql=sql,con=con,index_col='id')
con.close()
df
输出: