分享

pandas versus Excel 学习笔记11(多表联合查询)

 北方的白桦林 2020-05-15

Excel

VLOOKUP函数

=VLOOKUP(A2,Scores!A2:B21,2,0)#不做近似填充

pandas

merge函数

方法一

  1. students=pd.read_excel('016/Student_Score.xlsx',sheet_name='Students')
  2. scores=pd.read_excel('016/Student_Score.xlsx',sheet_name='Scores')
  3. table=students.merge(scores,on='ID')
  4. print(table)

方法二

如果!!ID设为索引后会从普通列中消失

  1. students=pd.read_excel('016/Student_Score.xlsx',sheet_name='Students',index_col='ID')
  2. scores=pd.read_excel('016/Student_Score.xlsx',sheet_name='Scores',index_col='ID')
  3. table=students.merge(scores,how='left',left_on=students.index,right_on=scores.index).fillna(0)
  4. table.Score=table.Score.astype(int)

默认状态,在scores中查不到的数据,自动舍掉

table=students.merge(scores,on='ID')

结果:

 保留students中所有数据

  1. table=students.merge(scores,how='left',on='ID').fillna(0)
  2. #将nan填为0

结果:

假设两张表中的参照列名不相同

  1. table=students.merge(scores,left_on='ID',right_on='FD')
  2. 类似这样

 不写 on='ID' 默认寻找相同数据列名

join函数

自动识别索引

  1. students=pd.read_excel('016/Student_Score.xlsx',sheet_name='Students',index_col='ID')
  2. scores=pd.read_excel('016/Student_Score.xlsx',sheet_name='Scores',index_col='ID')
  3. table=students.join(scores,how='left').fillna(0)
  4. table.Score=table.Score.astype(int)

join函数不再有

left_on='ID',right_on='FD'

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约