pandas的拼接操作
pandas拼接分为级联(pandas.concat,pandas.append) 以及合并(pandas.merge,,pandas.join)
# 导入模块、别名
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
# 定义生成DataFrame的函数:
def make_df(cols,index):
data = {col:[str(col)+str(ind) for ind in index] for col in cols}
df = DataFrame(data = data,columns = cols ,index = index )
return df
df1 = make_df(['a','b','c'],[1,2,3])
# 输出
a b c
1 a1 b1 c1
2 a2 b2 c2
3 a3 b3 c3
df2 = make_df(['a','b','c'],[4,5,6])
# 输出
a b c
4 a4 b4 c4
5 a5 b5 c5
6 a6 b6 c6
使用pandas.concat()级联
pandas使用pandas.concat函数,与numpy.concatenate函数类似,只是多了一些参数:
pandas.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
keys=None, levels=None, names=None, verify_integrity=False,
copy=True)
1、简单级联
和numpy.concatenate一样,优先增加行数(默认axis=0),numpy.concatenate(axis=1)的时候是水平的级联,numpy中没有index,和columns,所以只要行列相等就可以级联,在pandas中,如果行 和 列不一致,但是shape相同,会级联成一个更大的df,不对应的值会填充NaN。
pandas.concat([df1,df2],axis=1)
pd.concat([df1,df2],axis=0)
df3 = make_df(['a','b','c'],[2,3,4])
# 输出
a b c
2 a2 b2 c2
3 a3 b3 c3
4 a4 b4 c4
pd.concat([df1,df3],axis=1)
pd.concat([df1,df3],axis=0,ignore_index=True) #ignore_index 作用是对索引重新排序
pd.concat([df1,df3],axis=1)
df4 = pd.concat([df1,df3],keys=['期中','期末'])
2、 不匹配级联
不匹配指的是级联的维度的索引不一致。例如纵向级联时列索引不一致,横向级联时行索引不一致。
(1)外连接:补NaN(默认)
df1 = make_df(['a','b','c'],[1,2,3])
# 输出
a b c
1 a1 b1 c1
2 a2 b2 c2
3 a3 b3 c3
df5 = make_df(['c','d','e'],[3,4,5])
# 输出
c d e
3 c3 d3 e3
4 c4 d4 e4
5 c5 d5 e5
df6 = pd.concat([df1,df5],axis=1)
df6 = pd.concat([df1,df5],axis=0)
(2) 内连接:只连接匹配的项
df6 = pd.concat([df1,df5],axis=1,join='inner')
# 输出
a b c c d e
3 a3 b3 c3 c3 d3 e3
df1 = make_df(['a','b','c'],[1,2,3])
# 输出
a b c
1 a1 b1 c1
2 a2 b2 c2
3 a3 b3 c3
df5 = make_df(['c','d','e'],[3,4,5])
# 输出
c d e
3 c3 d3 e3
4 c4 d4 e4
5 c5 d5 e5
df7 = pd.concat([df1,df5],join_axes=[df1.columns])
#join_axes 的值是一个列表[df1.index]
3)、使用append()函数添加
append专门用于在后面添加,append 和 concat 相似。
df1 = make_df(['a','b','c'],[1,2,3])
# 输出
a b c
1 a1 b1 c1
2 a2 b2 c2
3 a3 b3 c3
df5 = make_df(['c','d','e'],[3,4,5])
# 输出
c d e
3 c3 d3 e3
4 c4 d4 e4
5 c5 d5 e5
df1.append(df5)