关于合并python DataFrame的方法总结

  小编写这篇文章的主要目的,主要是给大家做个详细的解答,详细的解答关于python DataFrame相关方面的知识,希望可以为各位读者带来更多的帮助。

  python DataFrame的合并方法

  Python的Pandas针对DataFrame,Series提供了多个合并函数,通过参数的调整可以轻松实现DatafFrame的合并。

  首先,定义3个DataFrame df1,df2,df3,进行concat、merge、append函数的实验。

  df1=pd.DataFrame([[1,2,3],[2,3,4]],columns=['a','b','c'])
  df2=pd.DataFrame([[2,3,4],[3,4,5]],columns=['a','b','c'])
  df3=pd.DataFrame([[1,2,3],[2,3,4]],columns=['a','b','d'])
  df1
  a b c
  0 1 2 3
  1 2 3 4
  df2
  a b c
  0 2 3 4
  1 3 4 5
  df3
  a b d
  0 1 2 3
  1 2 3 4

  #concat函数

  pandas中concat函数的完整表达,包含多个参数,常用的有axis,join,ignore_index.

  concat函数的第一个参数为objs,一般为一个list列表,包含要合并两个或多个DataFrame,多个Series

 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.axis表示合并方向,默认axis=0,两个DataFrame按照索引方向纵向合并,axis=1则会按照columns横向合并。

  pd.concat([df1,df2],axis=1)
  a b c a b c
  0 1 2 3 2 3 4
  1 2 3 4 3 4 5

  2.join表示合并方式,默认join=‘outer’,另外的取值为’inner’,只合并相同的部分,axis=0时合并结果为相同列名的数据,axis=1时为具有相同索引的数据

  pd.concat([df2,df3],axis=0,join='inner')
  a b
  0 2 3
  1 3 4
  0 1 2
  1 2 3
  pd.concat([df2,df3],axis=1,join='inner')
  a b c a b d
  0 2 3 4 1 2 3
  1 3 4 5 2 3 4

  3.ignore_index表示索引的合并方式,默认为False,会保留原df的索引,如果设置ignore_index=True,合并后的df会重置索引。

  pd.concat([df1,df2],ignore_index=True)
  a b c
  0 1 2 3
  1 2 3 4
  2 2 3 4
  3 3 4 5

  #merge函数

  merge函数是pandas提供的一种数据库式的合并方法。

  on可以指定合并的列、索引,how则是与数据库join函数相似,取值为left,right,outer,inner.left,right分别对应left outer join,right outer join.

 pandas.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):

  merge函数可以通过pandas.merge(df1,df2)、df1.merge(df2)两种形式来实现两个DataFrame的合并,df1.merge(df2)是默认left=self的情况。

  df_merge=df1.merge(df3,on=['a','b'])
  a b c d
  0 1 2 3 3
  1 2 3 4 4

  #append函数

  append函数是pandas针对DataFrame、Series等数据结构合并提供的函数。

df1.append(self,other,ignore_index=False,verify_integrity=False)

  df1.append(df2)与pd.concat([df1,df2],ignore_index=False)具有相同的合并结果

  df1.append(df2)
  a b c
  0 1 2 3
  1 2 3 4
  0 2 3 4
  1 3 4 5

  把两个dataframe合并成一个

  1.    merage

result=pd.merge(对象1,对象2,on='key')

  2.append

  result=df1.append(df2)
  result=df1.append([df2,df3])
  result=df1.append(df4,ignore_index=True)

  3.join

result=left.join(right,on=['key1','key2'],how='inner')

  4.concat

 pd.concat(objs,axis=0,join='outer',join_axes=None,ignore_index=False,
  keys=None,levels=None,names=None,verify_integrity=False,
  copy=True)
  frames=[df1,df2,df3]
  result=pd.concat(frames)
  result=pd.concat(frames,keys=['x','y','z'])
  result=pd.concat([df1,df4],ignore_index=True)

  上文就为大家介绍完毕了,希望能给大家带来一定的帮助。

原创文章,作者:网友投稿,如若转载,请注明出处:https://www.cloudads.cn/archives/3982.html

发表评论

登录后才能评论