python concat axis_Python的合并数据集

Python 的pandas能够通过一些内置的方式进行数据集的合并。Pandas.merge函数可以实现根据一个或多个键值关键的键值,将两个DataFrame进行连接,这一特性,特别类似于数据库的连接。他实现的其实就是数据库连接的操作。

现在我们按照数据库连接的逻辑,分开解释Pandas.merge的使用。

Join two dataframes along columns

1。inner join。跟我们熟知的一样,inner join实现的是两个集合的交集。

pd.merge(df1,df2,on=’key’)

pd.merge(df1,df2,on=’key’,how=’inner’)

df1,df2分别为不同的dataframe, ‘key’ 为指定关联的键值。如果两个frame有不同的键值,则

pd.merge(df1,df2,left_on=’lkey’,right_on=’rkey’)

例如:

python concat axis_Python的合并数据集

python concat axis_Python的合并数据集

python concat axis_Python的合并数据集
  1. outer join. 两个集合进行outer join,其中以一个集合的键值为关键点,

left outer join:pd.merge(df1,df2,on=’key’,how=’left’)

python concat axis_Python的合并数据集

right outer join: pd.merge(df1,df2,on=’key’,how=’right’)

python concat axis_Python的合并数据集full join: pd.merge(df1,df2,how=’outer’)

python concat axis_Python的合并数据集

多个键值相互关联,

pd.merge(left,right,on=[‘key1′,’key2′],how=’outer’)

python concat axis_Python的合并数据集

如果一个键值同时存在于两个Frame中,而且并不是关联的键值时,可以用

pd.merge(left,right,on=’key1′,suffixes=(‘_left’,’_right’))

python concat axis_Python的合并数据集

Merge on index

inner:pd.merge(left1,right1,left_on=’key’,right_index=True)

full:pd.merge(left1,right1,left_on=’key’,right_index=True,how=’outer’)

所有的和之前的join模式一样,但是需要制定left_index=True or right_index=True.

python concat axis_Python的合并数据集

python concat axis_Python的合并数据集

多层次INDEX merge:

index &key,

pd.merge(lefth,righth,left_on=[‘key1′,’key2’],right_index=True)

index&index,

pd.merge(lefth,righth,left_index=True,right_index=True,how=’outer’)

python concat axis_Python的合并数据集

python concat axis_Python的合并数据集

python concat axis_Python的合并数据集

Join two Dataframe along rows

pd.concat([S1,S2,S3])类似于Dataframe 的union all

python concat axis_Python的合并数据集

pd.concat([S1,S2,S3]) 类似于 full join,同样达到了join by columns的目的。

python concat axis_Python的合并数据集

Dataframe:列合并

pd.concat([df1,df2],axis=1,keys=[‘level1′,’level2’])

pd.concat({‘level1′:df1,’level2’:df2},axis=1)

python concat axis_Python的合并数据集

DataFrame 行合并

python concat axis_Python的合并数据集

Original: https://blog.csdn.net/weixin_39586649/article/details/114359658
Author: weixin_39586649
Title: python concat axis_Python的合并数据集

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/743673/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球