- Python+Office:轻松实现Python办公自动化
- 王国平
- 695字
- 2025-02-18 05:44:23
3.1 数据的读取
在分析数据之前,需要准备“食材”,也就是数据,主要包括商品的属性数据、客户的订单数据、客户的退单数据等。本节将介绍Python读取本地离线数据、Web在线数据、数据库数据等各种存储形式的数据。
3.1.1 读取本地离线数据
1.读取.txt格式的数据
使用Pandas库中的read_table()函数,Python可以直接读取.txt格式的数据,代码如下:

在JupyterLab中运行上述代码,输出结果如下所示。

2.读取.csv格式的数据
使用Pandas库中的read_csv()函数,Python可以直接读取.csv格式的数据,代码如下:

在JupyterLab中运行上述代码,输出结果如下所示。

3.读取Excel文件数据
使用Pandas库中的read_excel()函数,Python可以直接读取Excel文件数据,代码如下:

在JupyterLab中运行上述代码,输出结果如下所示。

3.1.2 读取Web在线数据
Python可以读取Web在线数据,这里选取的数据集是UCI上的红酒数据集,该数据集是对意大利同一地区种植的葡萄酒进行化学分析的结果,这些葡萄酒来自3个不同的品种,分析确定了3种葡萄酒中每种葡萄酒含有的13种成分的数量。不同种类的酒品,它的成分也会有所不同,通过对这些成分的分析就可以对不同的特定的葡萄酒进行分类分析,原始数据集共有178个样本数、3种数据类别,每个样本有13个属性。
Python读取红酒在线数据集的代码如下:

在JupyterLab中运行上述代码,输出结果如下所示。

3.1.3 读取常用数据库中的数据
1.读取MySQL数据库中的数据
Python可以直接读取MySQL数据库中的数据,连接之前需要安装pymysql库。例如,统计汇总数据库orders表中2020年不同类型商品的销售额和利润额,代码如下:

在JupyterLab中运行上述代码,输出结果如下所示。

2.读取SQL Server数据库中的数据
Python可以直接读取SQL Server数据库中的数据,连接之前需要安装pymssql库。例如,查询数据库orders表中2020年利润额在400元以上的所有订单,代码如下:

在JupyterLab中运行上述代码,输出结果如下所示。
