本篇文章主要介绍了pandas中对series和dataframe对象进行连接的方法:pd.append()和pd.concat(),文中通过示例代码对这两种方法进行了详细的介绍,希望能对各位python小白的学习有所帮助。
描述:append方法用以在表尾中添加新的行,并返回追加后的数据对象,若追加的行中存在原数据没有的列,会新增一列,并用nan填充;若追加的行数据中缺少原数据某列,同样以nan填充
语法:df.append(other, ignore_index=False, verify_integrity=False, sort=None)
参数说明:
下面对append方法的每个参数进行详细介绍:
第一个参数为other:要追加的数据,可以是dataframe,series,字典,列表甚至是元素;但前后类型要一致。
# 将数据追加到series <<< a=df.iloc[0,:] <<< b=df.iloc[6,:] <<< a.append(b) #需赋给新值,不改变原数组 A 0 B 1 C 2 D 3 E 4 F 5 A 36 B 37 C 38 D 39 E 40 F 41 dtype: int32 <<< a A 0 B 1 C 2 D 3 E 4 F 5 Name: S1, dtype: int32 <<< c=a.append(b) # 保存为c <<< c A 0 B 1 C 2 D 3 E 4 F 5 A 36 B 37 C 38 D 39 E 40 F 41 dtype: int32
# 将数据追加到dataframe <<< a=df.iloc[0:2,:] <<< b=df.iloc[4:6,:] <<< c=a.append(b) # 注意是纵向追加,不支持横向追加 <<< c A B C D E F S1 0 1 2 3 4 5 S2 6 7 8 9 10 11 S5 24 25 26 27 28 29 S6 30 31 32 33 34 35
注意:获取单行得到的结果是一维数组,当一维数组[6,:]和二维数组[2,6]追加时,会得到8*7的数组,匹配不上的地方用NA填充。
# 将二维数组追加到一维数组 <<< a=df.iloc[0,:] <<< b=df.iloc[4:6,:] <<< c=a.append(b) <<< c 0 A B C D E F A 0.0 NaN NaN NaN NaN NaN NaN B 1.0 NaN NaN NaN NaN NaN NaN C 2.0 NaN NaN NaN NaN NaN NaN D 3.0 NaN NaN NaN NaN NaN NaN E 4.0 NaN NaN NaN NaN NaN NaN F 5.0 NaN NaN NaN NaN NaN NaN S5 NaN 24.0 25.0 26.0 27.0 28.0 29.0 S6 NaN 30.0 31.0 32.0 33.0 34.0 35.0
# 列表追加到列表 <<< a=[] <<< b=df.iloc[6,:].tolist() <<< a.append(b) <<< a [[36, 37, 38, 39, 40, 41]] # 序列追加到列表 <<< a=[1,2,3,4,5,6,7] <<< b=df.iloc[6,:] <<< a.append(b) <<< a [1, 2, 3, 4, 5, 6, 7, A 36 B 37 C 38 D 39 E 40 F 41 Name: S7, dtype: int32]
<<< df1=pd.DataFrame() <<< a={'A':1,'B':2} <<< df1=df1.append(a,ignore_index=True) <<< df1 A B 0 1 2
append方法也可以将单个元素追加到列表(其他对象不行),会自动将单个元素转为列表对象,再进行追加操作
# 单个元素进行追加 <<< a=[1,2,3,4,5,6,7,8] <<< a.append(9) <<< a [1, 2, 3, 4, 5, 6, 7, 8, 9]
<<< df1=pd.DataFrame() <<< ser=pd.Series({"x":1,"y":2},name="a") <<< df1=df1.append(ser) <<< df1 x y a 1 2
如果不添加name,也可以添加参数ignore_index:
<<< df1=pd.DataFrame() <<< ser=pd.Series({"x":1,"y":2}) <<< df1=df1.append(ser,ignore_index=True) <<< df1 x y a 1 2
第二个参数:两个表的index是否有实际含义,默认ignore_index=False,若为True,表根据列名对齐合并,生成新的index。
<<< a=df.iloc[0:2,:] <<< b=df.iloc[4:6,:] <<< a.append(b,ignore_index=True) A B C D E F 0 0 1 2 3 4 5 1 6 7 8 9 10 11 2 24 25 26 27 28 29 3 30 31 32 33 34 35 <<< a=df.iloc[0:2,:] <<< b=df.iloc[4:6,:] <<< a.append(b) A B C D E F S1 0 1 2 3 4 5 S2 6 7 8 9 10 11 S5 24 25 26 27 28 29 S6 30 31 32 33 34 35
在dataframe中,使用append方法进行表合并时,二者匹配不上的地方用NAN填充。
<<< df1=df.copy() <<< df2=pd.DataFrame(np.arange(8).reshape(2,4),columns=<<<['s1','s2','s3','s4']) <<< df_new=df1.append(df2,ignore_index=True) <<< df_new A B C D E F S1 S2 s3 s4 0 0 1 2 3 4 5 NaN NaN NaN NaN 1 6 7 8 9 10 11 NaN NaN NaN NaN 2 12 13 14 15 16 17 NaN NaN NaN NaN 3 18 19 20 21 22 23 NaN NaN NaN NaN 4 24 25 26 27 28 29 NaN NaN NaN NaN 5 30 31 32 33 34 35 NaN NaN NaN NaN 6 36 37 38 39 40 41 NaN NaN NaN NaN 7 NaN NaN NaN NaN NaN NaN 0 1 2 3 8 NaN NaN NaN NaN NaN NaN 4 5 6 7
第三个参数为verify_integrity:默认为False 参数用于检查结果对象新连接轴上的索引是否有重复项,有的话引发 ValueError,可以看到这个参数的作用与ignore_index 是互斥的。 (如果 ignore_index = True ,则意味着index不能是重复的,而ignore_index = False ,则意味着index可以是重复的)
<<< df1=df.copy() <<< df2=pd.DataFrame(np.arange(8).reshape(2,4),columns= <<< ['G','H','I','J'],index=['S1','S8'],dtype=int) <<< pd.set_option('precision',0) <<< df_new=df1.append(df2,verify_integrity=False) <<< df_new A B C D E F G H I J S1 0 1 2 3 4 5 NaN NaN NaN NaN S2 6 7 8 9 10 11 NaN NaN NaN NaN S3 12 13 14 15 16 17 NaN NaN NaN NaN S4 18 19 20 21 22 23 NaN NaN NaN NaN S5 24 25 26 27 28 29 NaN NaN NaN NaN S6 30 31 32 33 34 35 NaN NaN NaN NaN S7 36 37 38 39 40 41 NaN NaN NaN NaN S1 NaN NaN NaN NaN NaN NaN 0 1 2 3 S8 NaN NaN NaN NaN NaN NaN 4 5 6 7
注意:当需要连接的两个表的index有重复值时,设置ignore_index = True则会报错。
第四个参数为sort:默认是False,该属性在pandas的0.23.0版本才有,若为True,则对两个表没匹配上的列名,进行排序,若为False,不排序。
<<< df1=pd.DataFrame(np.arange(8).reshape(2,4),columns= <<< ['A1','B1','C1','D1'],index=['S1','S2']) <<< df2=pd.DataFrame(np.arange(8).reshape(2,4),columns= <<< ['A2','B2','C2','D2'],index=['S1','S3']) <<< pd.set_option('precision',0) <<< df_new=df1.append(df2,sort=True) <<< df_new A1 A2 B1 B2 C1 C2 D1 D2 S1 0 NaN 1 NaN 2 NaN 3 NaN S2 4 NaN 5 NaN 6 NaN 7 NaN S1 NaN 0 NaN 1 NaN 2 NaN 3 S3 NaN 4 NaN 5 NaN 6 NaN 7
描述:concat方法用以将两个或多个pandas对象根据轴(横向/纵向)进行拼接,concat函数是在pandas命名空间下的方法,因此需要通过pd.concat()的方式来引用。
语法:pd.concat(‘objs’, ‘axis=0’, “join=‘outer’”, ‘join_axes=None’, ‘ignore_index=False’, ‘keys=None’, ‘levels=None’, ‘names=None’, ‘verify_integrity=False’, ‘sort=None’, ‘copy=True’)
常用参数:
下面,将对concat方法以上各个参数进行详细说明:
第一个要学习的参数为objs:要进行拼接的pandas对象,可用中括号[]将两个或多个对象括起来。
1)对series进行拼接
<<< ser1=pd.Series(np.arange(9)) <<< ser2=pd.Series(np.arange(9)) # 对两个series对象进行拼接 <<< pd.concat([ser1,ser2]) 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 dtype: int32
<<< df1=pd.DataFrame(np.arange(9).reshape(3,3),columns= <<< ['A','B','C'],index=['a','b','c']) <<< df2=pd.DataFrame(np.arange(9).reshape(3,3),columns= <<< ['D','E','F'],index=['e','f','g']) # 对两个DataFrame对象进行拼接 <<< pd.concat([df1,df2]) A B C D E F a 0 1 2 NaN NaN NaN b 3 4 5 NaN NaN NaN c 6 7 8 NaN NaN NaN e NaN NaN NaN 0 1 2 f NaN NaN NaN 3 4 5 g NaN NaN NaN 6 7 8
第二个要学习的参数为axis:指定对象按照那个轴进行拼接,默认为0(纵向拼接),1为横向横向拼接。
<<< df1=pd.DataFrame(np.arange(9).reshape(3,3),columns= <<< ['A','B','C'],index=['a','b','c']) <<< df2=pd.DataFrame(np.arange(9).reshape(3,3),columns= <<< ['D','E','F'],index=['a','b','d']) # 将数据对象df1和df2沿1轴进行拼接,即进行横向拼接 <<< pd.concat([df1,df2],axis=1) A B C D E F a 0 1 2 0 1 2 b 3 4 5 3 4 5 c 6 7 8 NaN NaN NaN d NaN NaN NaN 6 7 8
注意:当对Series进行拼接时,设置axis=0进行纵向拼接的结果对象为Series,设置axis=1进行横向拼接的结果对象为DataFrame。
<<< ser1=pd.Series(np.arange(9)) <<< ser2=pd.Series(np.arange(9)) # 对Series进行拼接纵向拼接,结果认为Series对象 <<< a=pd.concat([ser1,ser2],axis=0) <<< type(a) pandas.core.series.Series # 对Series进行拼接横向拼接,结果转换为DataFrame对象 <<< b=pd.concat([ser1,ser2],axis=1) <<< type(b) pandas.core.frame.DataFrame
第三个要学习的参数为join:拼接的方式,inner为交集,outer为并集,横向拼接时由index的交/并集决定,纵向拼接时由columns的交/并集决定,同时,如果join=outer,匹配不上的地方以nan填充。
<<< df1=pd.DataFrame(np.arange(9).reshape(3,3),columns= <<< ['A','B','C'],index=['a','b','c']) <<< df2=pd.DataFrame(np.arange(9).reshape(3,3),columns= <<< ['D','E','F'],index=['a','b','d']) # 将df1和df2进行横向合并,取二者的并集 <<< pd.concat([df1,df2],axis=1) A B C D E F a 0 1 2 0 1 2 b 3 4 5 3 4 5 c 6 7 8 NaN NaN NaN d NaN NaN NaN 6 7 8 # 将df1和df2进行横向合并,只取二者的交集 <<< pd.concat([df1,df2],axis=1,join='inner') A B C D E F a 0 1 2 0 1 2 b 3 4 5 3 4 5
第四个要学习的参数为join_axes:以哪个数据对象的index/columns作为轴进行拼接,当进行横向拼接时,join_axes为index的列表,如需根据df1对齐数据,则会保留df1的index,再将df2的数据进行拼接;同理,纵向拼接时为columns的列表。
<<< df1=pd.DataFrame(np.arange(9).reshape(3,3),columns= <<< ['A','B','C'],index=['a','b','c']) <<< df2=pd.DataFrame(np.arange(9).reshape(3,3),columns= <<< ['D','E','F'],index=['a','b','d']) # 根据df1的index对齐数据 <<< pd.concat([df1,df2],axis=1,join_axes=[df1.index]) A B C D E F a 0 1 2 0 1 2 b 3 4 5 3 4 5 c 6 7 8 NaN NaN NaN # 根据df2的index对齐数据 <<< pd.concat([df1,df2],axis=1,join_axes=[df2.index]) A B C D E F a 0 1 2 0 1 2 b 3 4 5 3 4 5 d NaN NaN NaN 6 7 8
第五个要学习的参数为ignore_index:默认为False,如果设置为true,则无视表原来的轴标签,直接合并,合并后生成新的轴标签。
这里需要注意的是,与append方法只能进行纵向拼接不同,concat方法既可以进行横向拼接,也可以进行纵向拼接,若设置ignore_index=True,当进行横向拼接时,则无视原表的columns,直接合并,合并后生成默认的columns;同理,当进行纵向拼接时,则是忽略原表的index,生成新的index。
<<< df1=pd.DataFrame(np.arange(9).reshape(3,3),columns= <<< ['A','B','C'],index=['a','b','c']) <<< df2=pd.DataFrame(np.arange(9).reshape(3,3),columns= <<< ['D','E','F'],index=['a','b','d']) # 横向拼接时,忽略的是columns,index仍起作用 <<< pd.concat([df1,df2],axis=1,ignore_index=True) 0 1 2 3 4 5 a 0 1 2 0 1 2 b 3 4 5 3 4 5 c 6 7 8 NaN NaN NaN d NaN NaN NaN 6 7 8 # 纵向拼接时,忽略的是index,columns仍起作用 pd.concat([df1,df2],axis=0,ignore_index=True) 0 1 2 3 4 5 a 0 1 2 0 1 2 b 3 4 5 3 4 5 c 6 7 8 NaN NaN NaN d NaN NaN NaN 6 7 8
第六个要学习的参数为keys:表标识的列表,用来区分合并后的数据来源于哪个表,当ignore_index=True时,此参数的作用失效。
<<< df1=pd.DataFrame(np.arange(9).reshape(3,3),columns= <<< ['A','B','C'],index=['a','b','c']) <<< df2=pd.DataFrame(np.arange(9).reshape(3,3),columns= <<< ['D','E','F'],index=['a','b','d']) # 设置ignore_index=True时,参数keys不起作用 <<< pd.concat([df1,df2],axis=1,ignore_index=True,keys= <<< ['df1','df2']) 0 1 2 3 4 5 a 0 1 2 0 1 2 b 3 4 5 3 4 5 c 6 7 8 NaN NaN NaN d NaN NaN NaN 6 7 8 # 设置ignore_index=False,会根据keys的列表标识结果中的数据来源 <<< pd.concat([df1,df2],axis=1,ignore_index=False,keys= <<< ['df1','df2']) df1 df2 A B C D E F a 0 1 2 0 1 2 b 3 4 5 3 4 5 c 6 7 8 NaN NaN NaN d NaN NaN NaN 6 7 8
总结:
如对append和concat方法还感兴趣,建议可前往查看官方文档:
1)https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html?highlight=append#pandas.DataFrame.append
数据分析咨询请扫描二维码