Python数据分析 知识量:13 - 56 - 232
纵向拼接与横向拼接相对应,是指两个表在垂直方向上进行拼接。纵向拼接一般要求拼接的两个表具有相同的结构,即它们的列应该是一样的。
纵向拼接使用concat()函数来实现。
普通拼接时直接将要拼接的表以列表的形式传递给concat()函数。
import pandas as pd df1=pd.read_excel(r"D:\PythonTestFile\pinjie1.xlsx") df2=pd.read_excel(r"D:\PythonTestFile\pinjie2.xlsx") print(df1,'\n') print(df2,'\n') print(pd.concat([df1,df2]))
运行结果为:
Name Sex Age Chinese English Math 0 Noah male 15 90 50 66 1 Emma female 16 56 56 55 2 Bob male 15 99 84 89 3 Olivia female 17 86 87 44 Name Sex Age Chinese English Math 0 Jeff male 16 48 87 65 1 Liam male 14 55 88 69 2 Sophia female 15 90 66 96 3 Isabella female 16 66 85 55 Name Sex Age Chinese English Math 0 Noah male 15 90 50 66 1 Emma female 16 56 56 55 2 Bob male 15 99 84 89 3 Olivia female 17 86 87 44 0 Jeff male 16 48 87 65 1 Liam male 14 55 88 69 2 Sophia female 15 90 66 96 3 Isabella female 16 66 85 55
普通拼接后,索引列的值很可能会错乱,这时可以通过设置参数ignore_index=True来重置索引。
import pandas as pd df1=pd.read_excel(r"D:\PythonTestFile\pinjie1.xlsx") df2=pd.read_excel(r"D:\PythonTestFile\pinjie2.xlsx") print(df1,'\n') print(df2,'\n') print(pd.concat([df1,df2],ignore_index=True))
运行结果为:
Name Sex Age Chinese English Math 0 Noah male 15 90 50 66 1 Emma female 16 56 56 55 2 Bob male 15 99 84 89 3 Olivia female 17 86 87 44 Name Sex Age Chinese English Math 0 Jeff male 16 48 87 65 1 Liam male 14 55 88 69 2 Sophia female 15 90 66 96 3 Isabella female 16 66 85 55 Name Sex Age Chinese English Math 0 Noah male 15 90 50 66 1 Emma female 16 56 56 55 2 Bob male 15 99 84 89 3 Olivia female 17 86 87 44 4 Jeff male 16 48 87 65 5 Liam male 14 55 88 69 6 Sophia female 15 90 66 96 7 Isabella female 16 66 85 55
当拼接的表中含有重复行时,可以通过drop_duplicates()函数来消除重复数据。
import pandas as pd df1=pd.read_excel(r"D:\PythonTestFile\pinjie1.xlsx") df2=pd.read_excel(r"D:\PythonTestFile\pinjie2.xlsx") print(df1,'\n') print(df2,'\n') print(pd.concat([df1,df2],ignore_index=True),'\n') print(pd.concat([df1,df2],ignore_index=True).drop_duplicates()) # 消除重复值
运行结果为:
Name Sex Age Chinese English Math 0 Noah male 15 90 50 66 1 Emma female 16 56 56 55 2 Bob male 15 99 84 89 3 Olivia female 17 86 87 44 Name Sex Age Chinese English Math 0 Jeff male 16 48 87 65 1 Bob male 15 99 84 89 2 Olivia female 17 86 87 44 3 Isabella female 16 66 85 55 Name Sex Age Chinese English Math 0 Noah male 15 90 50 66 1 Emma female 16 56 56 55 2 Bob male 15 99 84 89 3 Olivia female 17 86 87 44 4 Jeff male 16 48 87 65 5 Bob male 15 99 84 89 6 Olivia female 17 86 87 44 7 Isabella female 16 66 85 55 Name Sex Age Chinese English Math 0 Noah male 15 90 50 66 1 Emma female 16 56 56 55 2 Bob male 15 99 84 89 3 Olivia female 17 86 87 44 4 Jeff male 16 48 87 65 7 Isabella female 16 66 85 55
Copyright © 2017-Now pnotes.cn. All Rights Reserved.
编程学习笔记 保留所有权利
MARK:3.0.0.20240214.P35
From 2017.2.6