准备工作:下载示例数据,提取码:tkqn 数据例子
在数据合并中,有merge和concat是比较常用的。
merge:左连、右连、内连
新建两个dataframe数据集:
import pandas as pd
df1 = pd.DataFrame({'key1':['b','b','a','a','b','a','c'],'key2':['i','j','k','k','i','j','k'],'data1':range(7)})
df2 = pd.DataFrame({'key1':['a','b','d'],'key2':['k','j','i'],'data2':range(3)})
- 以索引进行合并
merge1 = pd.merge(df1,df2,how='left',left_index=True,right_index=True) #index 左连
merge2 = pd.merge(df1,df2,how='right',left_index=True,right_index=True) #index 右连
merge3 = pd.merge(df1,df2,how='inner',left_index=True,right_index=True) #index 内连
因为两个df都有key1、key2列,所以连接之后,以x、y后缀去区分。当然也可以自定义后缀:
merge4 = pd.merge(df1,df2,how='inner',left_index=True,right_index=True,suffixes=('左','右')) #index 自定义后缀
- 以某一列为连接键进行合并
比如以key1列进行合并
merge5 = pd.merge(df1,df2,left_on='key1',right_on='key1',how='left') #key1 左连
- 以某两列为连接键进行合并
实际中挺常见的,比如先按日期,再按部门。
merge6 = pd.merge(df1,df2,on=['key1','key2'],how='inner') #key1 key2 内连
concat:横向合并、纵向合并
- 纵向合并:
concat1 = pd.concat([df1,df2],axis=0) #纵向合并,保留原来的index
concat2 = pd.concat([df1,df2],axis=0,ignore_index=True) #纵向合并,重新赋值inde
- 横向合并,相当于merge(index=True)
concat3 = pd.concat([df1,df2],axis=1) #横向合并,以index为连接键
concat可以多个df进行连接,[df1,df2,df3...]
append
append和concat纵向合并类似:df1.append(df2, ignore_index=True)
专栏列表
数据分析与Python:【Python代替Excel】1:Python与Anaconda
数据分析与Python:【Python代替Excel】2:数据的读取
数据分析与Python:【Python代替Excel】3:数据的预览
数据分析与Python:【Python代替Excel】4:数据的清洗
数据分析与Python:【Python代替Excel】5:数据的统计分析
数据分析与Python:【Python代替Excel】6:按条件筛选