Pandas提供了concat、append、join和merge四种方法用于dataframe的拼接,其大致特点和区别见下表:
.concat() | pandas的顶级方法,提供了axis设置可用于df间行方向(增加行,下同)或列方向(增加列,下同)进行内联或外联拼接操作 |
---|---|
.append() | dataframe数据类型的方法,提供了行方向的拼接操作 |
.join() | dataframe数据类型的方法,提供了列方向的拼接操作,支持左联、右联、内联和外联四种操作类型 |
.merge() | pandas的顶级方法,提供了类似于SQL数据库连接操作的功能,支持左联、右联、内联和外联等全部四种SQL连接操作类型 |
1. pd.concat()
concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
keys=None, levels=None, names=None, verify_integrity=False,
copy=True)
"""
常用参数说明:
axis:拼接轴方向,默认为0,沿行拼接;若为1,沿列拼接
join:默认外联'outer',拼接另一轴所有的label,缺失值用NaN填充;内联'inner',只拼接另一轴相同的label;
join_axes: 指定需要拼接的轴的labels,可在join既不内联又不外联的时候使用
ignore_index:对index进行重新排序
keys:多重索引
"""
- 示例
>>> import pandas as pd
>>> def df_maker(cols, idxs):
return pd.DataFrame({c:[c+str(i) for i in idxs] for c in cols}, index=idxs)
>>> df1 = df_maker('abc',[1,2,3])
>>> df1
a b c
1 a1 b1 c1
2 a2 b2 c2
3 a3 b3 c3
>>> df2 = df_maker('cde',[3,4,5])
>>> df2
c d e
3 c3 d3 e3
4 c4 d4 e4
5 c5 d5 e5
>>> pd.concat([df1,df2]) # 默认沿axis=0,join=‘out’的方式进行concat
a b c d e
1 a1 b1 c1 NaN NaN
2 a2 b2 c2 NaN NaN
3 a3 b3 c3 NaN NaN
3 NaN NaN c3 d3 e3
4 NaN NaN c4 d4 e4
5 NaN NaN c5 d5 e5
>>> pd.concat([df1,df2], ignore_index=True) # 重新设定index(效果类似于pd.concat([df1,df2]).reset_index(drop=True))
a b c d e
0 a1 b1 c1 NaN NaN
1 a2 b2 c2 NaN NaN
2 a3 b3 c3 NaN NaN
3 NaN NaN c3 d3 e3
4 NaN NaN c4 d4 e4
5 NaN NaN c5 d5 e5
>>> pd.concat([df1,df2], axis=1) # 沿列进行合并
a b c c d e
1 a1 b1 c1 NaN NaN NaN
2 a2 b2 c2 NaN NaN NaN
3 a3 b3 c3 c3 d3 e3
4 NaN NaN NaN c4 d4 e4
5 NaN NaN NaN c5 d5 e5
>>> pd.concat([df1,df2], axis=1, join='inner') # 沿列进行合并,采用外联方式因为行中只有index=3是重复的,所以只有一行
a b c c d e
3 a3 b3 c3 c3 d3 e3
>>> pd.concat([df1,df2], axis=1, join_axes=[df1.index]) # 指定只取df1的index
a b c c d e
1 a1 b1 c1 NaN NaN NaN
2 a2 b2 c2 NaN NaN NaN
3 a3 b3 c3 c3 d3 e3
>>> from pandas import Index
>>> index = Index([1,2,4])
>>> pd.concat([df1,df2], axis=1, join_axes=[index]) # 自定义index
a b c c d e
1 a1 b1 c1 NaN NaN NaN
2 a2 b2 c2 NaN NaN NaN
4 NaN NaN NaN c4 d4 e4
>>> pd.concat([df1,df2], axis=0,keys=["第一组","第二组"]) # 通过key定义多重索引
a b c d e
第一组 1 a1 b1 c1 NaN NaN
2 a2 b2 c2 NaN NaN
3 a3 b3 c3 NaN NaN
第二组 3 NaN NaN c3 d3 e3
4 NaN NaN c4 d4 e4
5 NaN NaN c5 d5 e5
2. df.append
append(self, other, ignore_index=False, verify_integrity=False)
"""
常用参数说明:
other:另一个df
ignore_index:若为True,则对index进行重排
verify_integrity:对index的唯一性进行验证,若有重复,报错。若已经设置了ignore_index,则该参数无效
"""
- 示例
>>> import pandas as pd
>>> def df_maker(cols, idxs):
return pd.DataFrame({c:[c+str(i) for i in idxs] for c in cols}, index=idxs)
>>> df1 = df_maker('abc',[1,2,3])
>>> df1
a b c
1 a1 b1 c1
2 a2 b2 c2
3 a3 b3 c3
>>> df2 = df_maker('cde',[3,4,5])
>>> df2
c d e
3 c3 d3 e3
4 c4 d4 e4
5 c5 d5 e5
>>> df1.append(df2) # 效果类似于pd.concat([df1,df2])
a b c d e
0 a1 b1 c1 NaN NaN
1 a2 b2 c2 NaN NaN
2 a3 b3 c3 NaN NaN
3 NaN NaN c3 d3 e3
4 NaN NaN c4 d4 e4
5 NaN NaN c5 d5 e5
>>> df1.append(df2,ignore_index=True) # index重排,效果类似于pd.concat([df1, df2], ignore_index=True)
a b c d e
0 a1 b1 c1 NaN NaN
1 a2 b2 c2 NaN NaN
2 a3 b3 c3 NaN NaN
3 NaN NaN c3 d3 e3
4 NaN NaN c4 d4 e4
5 NaN NaN c5 d5 e5
>>> df1.append(df2,verify_integrity=True) # 因为两个df均有index=3,所以报错
3. df.join()
join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False)
"""
常用参数说明:
on:参照的左边df列名key(可能需要先进行set_index操作),若未指明,按照index进行join
how:{‘left’, ‘right’, ‘outer’, ‘inner’}, 默认‘left’,即按照左边df的index(若声明了on,则按照对应的列);若为‘right’abs照左边的df
若‘inner’为内联方式;若为‘outer’为全连联方式。
sort:是否按照join的key对应的值大小进行排序,默认False
lsuffix,rsuffix:当left和right两个df的列名出现冲突时候,通过设定后缀的方式避免错误
"""
- 示例
>>> import pandas as pd
>>> import numpy as np
>>> df3 = pd.DataFrame({'lkey':['foo','bar','baz','foo'], 'value':np.arange(1,5)})
>>> df3
lkey value
0 foo 1
1 bar 2
2 baz 3
3 foo 4
>>> df4 = pd.DataFrame({'rkey':['foo','bar','qux','bar'], 'value':np.arange(3,7)})
>>> df4
lkey value
0 foo 3
1 bar 4
2 qux 5
3 bar 6
>>> df3.join(df4) # 两者有相同的列名‘value’,所以报错
>>> df3.join(df4 , lsuffix='_df3', rsuffix='_df4') # 通过添加后缀避免冲突
lkey value_df3 rkey value_df4
0 foo 1 foo 3
1 bar 2 bar 4
2 baz 3 qux 5
3 foo 4 bar 6
>>> df3.set_index('lkey').join(df4.set_index('rkey'), how='outer',lsuffix='_df3',rsuffix='_df4') # 可以通过将两边的key进行set_index
value_df3 value_df4
bar 2.0 4.0
bar 2.0 6.0
baz 3.0 NaN
foo 1.0 3.0
foo 4.0 3.0
qux NaN 5.0
>>> df3.join(df4.set_index('rkey'), on='lkey',lsuffix='_df3',rsuffix='_df4') # 也可以通过设置后边df中key,并通过on与指定的左边df中的列进行合并,返回的index不变
lkey value_df3 value_df4
0 foo 1 3.0
1 bar 2 4.0
1 bar 2 6.0
2 baz 3 NaN
3 foo 4 3.0
4. pd.merge()
pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None,
left_index=False, right_index=False, sort=False,
suffixes=('_x', '_y'), copy=True, indicator=False,
validate=None):
"""
既可作为pandas的顶级方法使用,也可作为DataFrame数据结构的方法进行调用
常用参数说明:
how:{'left’, ‘right’, ‘outer’, ‘inner’}, 默认‘inner’,类似于SQL的内联。'left’类似于SQL的左联;'right’类似于SQL的右联;
‘outer’类似于SQL的全联。
on:进行合并的参照列名,必须一样。若为None,方法会自动匹配两张表中相同的列名
left_on: 左边df进行连接的列
right_on: 右边df进行连接的列
suffixes: 左、右列名称前缀
validate:默认None,可定义为“one_to_one” 、“one_to_many” 、“many_to_one”和“many_to_many”,即验证是否一对一、一对多、多对一或
多对多关系
"""
"""
SQL语句复习:
内联:SELECT a.*, b.* from table1 as a inner join table2 as b on a.ID=b.ID
左联:SELECT a.*, b.* from table1 as a left join table2 as b on a.ID=b.ID
右联:SELECT a.*, b.* from table1 as a right join table2 as b on a.ID=b.ID
全联:SELECT a.*, b.* from table1 as a full join table2 as b on a.ID=b.ID
"""
- 示例
>>> import pandas as pd
>>> df3 = pd.DataFrame({'lkey':['foo','bar','baz','foo'], 'value':np.arange(1,5)})
>>> df3
lkey value
0 foo 1
1 bar 2
2 baz 3
3 foo 4
>>> df4 = pd.DataFrame({'rkey':['foo','bar','qux','bar'], 'value':np.arange(3,7)})
>>> df4
lkey value
0 foo 3
1 bar 4
2 qux 5
3 bar 6
>>> pd.merge(df3,df4) # on为None,自动找寻相同的列名,即为'value',且默认为内联
lkey value rkey
0 baz 3 foo
1 foo 4 bar
>>> pd.merge(df3,df4,how='outer') # 外联模式下
lkey value rkey
0 foo 1 NaN
1 bar 2 NaN
2 baz 3 foo
3 foo 4 bar
4 NaN 5 qux
5 NaN 6 bar
>>> pd.merge(df3, df4, left_on='lkey',right_on='rkey') # 默认内联,2个foo*2个bar
lkey value_x rkey value_y
0 foo 1 foo 3
1 foo 4 foo 3
2 bar 2 bar 4
3 bar 2 bar 6
>>> pd.merge(df3, df4, left_on='lkey',right_on='rkey', how='left') # 以左边的df3为标准进行连接
lkey value_x rkey value_y
0 foo 1 foo 3.0
1 bar 2 bar 4.0
2 bar 2 bar 6.0
3 baz 3 NaN NaN
4 foo 4 foo 3.0
>>> pd.merge(df3, df4, left_on='lkey',right_on='rkey', how='right') # 以右边的df4为标准进行连接
lkey value_x rkey value_y
0 foo 1.0 foo 3
1 foo 4.0 foo 3
2 bar 2.0 bar 4
3 bar 2.0 bar 6
4 NaN NaN qux 5
>>> pd.merge(df3, df4, left_on='lkey',right_on='rkey', how='outer') # 全连接
lkey value_x rkey value_y
0 foo 1.0 foo 3.0
1 foo 4.0 foo 3.0
2 bar 2.0 bar 4.0
3 bar 2.0 bar 6.0
4 baz 3.0 NaN NaN
5 NaN NaN qux 5.0
源代码文件见:https://github.com/guofei1989/python_func_cases/blob/master/pandas_demos/combine_ops.ipynb