
3.8 数据的合并
数据合并就是将不同数据源或数据表中的数据整合到一起,本节将介绍横向合并merge()函数和纵向合并concat()函数,使用的数据文件为“2020年第二学期学生考试成绩.xls”。
3.8.1 merge()函数:横向合并
Pandas库中的数据可以通过一些方式进行合并。
● merge()函数根据一个或多个键将不同数据集中的行连接起来。
● concat()函数可以沿着某条轴线,将多个对象堆叠到一起。
在介绍数据合并之前,创建一个关于4名学生学习成绩的数据集,代码如下:

运行上述代码,创建的数据集如下所示。

再创建一个关于4名学生学习成绩的数据集,代码如下:

运行上述代码,创建的数据集如下所示。

使用merge()函数横向合并两个数据集,代码如下:

代码输出结果如下所示。

如果没有指明使用哪个列连接,则横向连接会重叠列的列名。可以通过参数on指定合并所依据的关键字段。例如,指定课程,代码如下:

代码输出结果如下所示。

由于演示的需要,下面再创建一个关于4名学生学习成绩的数据集,代码如下:

如果两个数据集中的关键字段名称不同时,则需要使用left_on和right_on,代码如下:

代码输出结果如下所示。

在默认情况下,横向连接merge()函数使用的是“内连接(inner)”,即输出的是两个数据集的交集。其他方式还有“left”、“right”及“outer”,这个与数据库中的表连接基本类似。内连接代码如下:

代码输出结果如下所示。

左连接是左边的数据集不加限制,右边的数据集仅会显示与左边相关的数据,代码如下:

代码输出结果如下所示。

右连接是右边的数据集不加限制,左边的数据集仅会显示与右边相关的数据,代码如下:

代码输出结果如下所示。

外连接输出的是两个数据集的并集,组合了左连接和右连接的效果,代码如下:

代码输出结果如下所示。

3.8.2 concat()函数:纵向合并
在介绍纵向连接之前,创建两个关于4名学生学习成绩的数据集,代码如下:

使用concat()函数可以实现数据集的纵向合并,代码如下:

代码输出结果如下所示。
