第6天|16天搞定Python数据分析,Pandas读数据
在进行数据分析时,用随机生成的数据,其实并没有多大的意义。有意义的数据,大多数是存在数据库(db)、文件(excel等),还有就是网络(html、json或xml)中的。有关文件的操作和解析,在学习Python基础和网络爬虫时,就讲过了,在这就不再讲解了。
这次要讲解的是,Pandas读取excel、db等文件数据之后,转换成Series或DataFrame,作为matplotlib等数据源的内容。
6.1 读excel
pandas读取存储在Excel 2003(或更高版本)中的表格数据,用的是第3方扩展包xlrd,在使用之前,你需要用pip/pip3 install xlrd命令进行安装。
import matplotlib.pyplot as plt
import pandas as pd
""" Windows系统用
# plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False"""
# macOS系统用
plt.rcParams["font.sans-serif"] = "Songti SC"
plt.rcParams["axes.unicode_minus"] = False
# 指定画布大小,默认为600*480
fig, axes = plt.subplots(figsize=(9, 6))
data = pd.read_excel("销售统计.xlsx", "Sheet1", index_col="日期")
df = pd.DataFrame(data)
print(df)
# 底部标签旋转(倾斜)360°
df.plot.bar(ax=axes, rot="360")
# 保存图片
fig.savefig("test.png")
输出结果
6.2 读数据库
pandas操作数据库,用的是第3方的SQLAlchemy,它是一个很流行的Python SQL工具,借助它,pandas可以让你轻松的从SQLAlchemy连接读取数据。有关数据表的创建,还是用之前《第11天 | 12天搞定Python,数据库操作 》的方式。
在使用SQLAlchemy之前,你得先用pip/pip3 install SQLAlchemy命令进行安装。
import sqlite3
import sqlalchemy as sqla
import matplotlib.pyplot as plt
import pandas as pd
def create_data():
# 创建一个数据库
conn = sqlite3.connect("sales.db")
# 创建游标
cursor = conn.cursor()
# 执行语句创建表的语句
create_table = "Create Table Orders(id int, periods text, phone double, pad double, computer double)"
cursor.execute(create_table)
# 添加多条数据
cursor.executemany("INSERT INTO Orders VALUES (?,?,?,?,?)",
[(1, 7, 12, 10, 13),
(2, 8, 20, 11, 9),
(3, 9, 16, 12, 8),
(4, 10, 13, 10, 6)])
conn.commit()
# 关闭数据库的链接
cursor.close()
conn.close()
def analysis():
""" Windows系统用
# plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False"""
# macOS系统用
plt.rcParams["font.sans-serif"] = "Songti SC"
plt.rcParams["axes.unicode_minus"] = False
# 指定画布大小,默认为600*480
fig, axes = plt.subplots(figsize=(9, 6))
db = sqla.create_engine("sqlite:///sales.db")
df = pd.read_sql("select periods ,phone , pad, computer from Orders", db, index_col="periods")
df.plot.barh(ax=axes, stacked=True)
# 保存图片
fig.savefig("test.png")
if __name__ == '__main__':
# 创建数据表
create_data()
# 数据分析
analysis()
输出结果
好了,有关Pandas读数据的内容,老陈讲完了,如果觉得对你有所帮助,希望老铁能转发点赞,让更多的人看到这篇文章。你的转发和点赞,就是对老陈继续创作和分享最大的鼓励。
一个当了10年技术总监的老家伙,分享多年的编程经验。想学编程的朋友,可关注今日头条:老陈说编程。分享Python,前端(小程序)、App和嵌入式方面的干货。关注我,没错的。