栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pandas的数据融合和拼接操作示例

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pandas的数据融合和拼接操作示例

import pandas as pd

se1=pd.Series({'ID':'x','a':1,'b':20})
se2=pd.Series({'ID':'x','c':1,'d':20})
df1=pd.Dataframe({'ID':['x','y','z'],'a':[1,2,3],'b':[1,2,3]})
df2=pd.Dataframe({'ID':['x','m','n'],'c':[1,2,3],'d':[1,2,3]})
print('print(pd.concat([se1,se2],axis=1).T)')
print(pd.concat([se1,se2],axis=1).T)
print("pd.merge(df1,df2,on='ID',how='inner')")#用双引号
print(pd.merge(df1,df2,on='ID',how='inner'))
print("pd.merge(df1,df2,on='ID',how='outer')")#用双引号
print(pd.merge(df1,df2,on='ID',how='outer'))
print("pd.merge(df1,df2,on='ID',how='right')")#用双引号
print(pd.merge(df1,df2,on='ID',how='right'))
print("pd.merge(df1,df2,on='ID',how='left')")#用双引号
print(pd.merge(df1,df2,on='ID',how='left'))
print("pd.concat([df1,df2],axis=0,join='outer',ignore_index=False)")
print(pd.concat([df1,df2],axis=0,join='outer',ignore_index=False))
print("pd.concat([df1,df2],axis=0,join='inner',ignore_index=False)")
pd.concat([df1,df2],axis=0,join='inner',ignore_index=False)

结果:

print(pd.concat([se1,se2],axis=1).T)
  ID    a    b    c    d
0  x    1   20  NaN  NaN
1  x  NaN  NaN    1   20
pd.merge(df1,df2,on='ID',how='inner')
  ID  a  b  c  d
0  x  1  1  1  1
pd.merge(df1,df2,on='ID',how='outer')
  ID    a    b    c    d
0  x  1.0  1.0  1.0  1.0
1  y  2.0  2.0  NaN  NaN
2  z  3.0  3.0  NaN  NaN
3  m  NaN  NaN  2.0  2.0
4  n  NaN  NaN  3.0  3.0
pd.merge(df1,df2,on='ID',how='right')
  ID    a    b  c  d
0  x  1.0  1.0  1  1
1  m  NaN  NaN  2  2
2  n  NaN  NaN  3  3
pd.merge(df1,df2,on='ID',how='left')
  ID  a  b    c    d
0  x  1  1  1.0  1.0
1  y  2  2  NaN  NaN
2  z  3  3  NaN  NaN
pd.concat([df1,df2],axis=0,join='outer',ignore_index=False)
  ID    a    b    c    d
0  x  1.0  1.0  NaN  NaN
1  y  2.0  2.0  NaN  NaN
2  z  3.0  3.0  NaN  NaN
0  x  NaN  NaN  1.0  1.0
1  m  NaN  NaN  2.0  2.0
2  n  NaN  NaN  3.0  3.0
pd.concat([df1,df2],axis=0,join='inner',ignore_index=False)
  ID
0  x
1  y
2  z
0  x
1  m
2  n
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/283612.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号