Pandas 数据合并与拼接
df1.append(df2):将df2中的行添加到df1的尾部
df.concat([df1, df2],axis=1):将df2中的列添加到df1的尾部
df1.join(df2,on=col1,how='inner'):对df1的列和df2的列执行SQL形式的join
Merge方法
pandas的Merge方法基于共同列,将两个DataFrame连接起来。有如下参数
- left/right :左右位置的dataframe
- how : {‘left’,‘right’,‘outer’,‘inner’,‘cross’}
- on: 需要合并的列名和索引名,若为None则默认为交集
- left_on/right_on: 左右data_frame合并的列名,可为索引,数组,列表
- left_index/right_index:是否以index为数组合并的列名,True表示是
- sort:根据dataframe合并的keys排序,默认是
- copy:如果False,避免可能的copy
- indicator:如果指定,检查是否为指定的类型
df1 = pd.DataFrame({'lkey': ['foo', 'bar', 'baz', 'foo'],
'value': [1, 2, 3, 5]})
df2 = pd.DataFrame({'rkey': ['foo', 'bar', 'baz', 'foo'],
'value': [5, 6, 7, 8]})
df1
lkey value
0 foo 1
1 bar 2
2 baz 3
3 foo 5
df2
rkey value
0 foo 5
1 bar 6
2 baz 7
3 foo 8
df1.merge(df2, left_on='lkey', right_on='rkey')
lkey value_x rkey value_y
0 foo 1 foo 5
1 foo 1 foo 8
2 foo 5 foo 5
3 foo 5 foo 8
4 bar 2 bar 6
5 baz 3 baz 7
join方法
join方法基于index连接dataframe,merge则是基于column,连接方法与merge一致
df1.append(df2):将df2中的行添加到df1的尾部
df.concat([df1, df2],axis=1):将df2中的列添加到df1的尾部
df1.join(df2,on=col1,how='inner'):对df1的列和df2的列执行SQL形式的join
contact方法
沿特定轴连接pandas对象和其他对象
- axis:连接所沿的轴
- ignore_index:如果是True,忽略串联轴所用索引值
- keys:如果通过多个,应包含元组
- levels:特殊的索引用以构造多组别
s1 = pd.Series(['a', 'b'])
s2 = pd.Series(['c', 'd'])
pd.concat([s1, s2])
0 a
1 b
0 c
1 d
dtype: object
pd.concat([s1, s2], keys=['s1', 's2'],
names=['Series name', 'Row ID'])
Series name Row ID
s1 0 a
1 b
s2 0 c
1 d
dtype: object