首页 > 其他 > 详细

Pandas_两表联合(类似excel的vlookup操作)

时间:2019-05-03 01:24:47      阅读:652      评论:0      收藏:0      [点我收藏+]

 student表:

技术分享图片

 

score表:

技术分享图片

 

要求从students表里查出每个学生对应的成绩 

import pandas as pd

students = pd.read_excel("../016/Student_Score.xlsx",sheet_name="Students")
scores = pd.read_excel("../016/Student_Score.xlsx",sheet_name="Scores")
print(students.dtypes)
print(scores.dtypes)

 

 

# 思路:将学生表和成绩表联合起来,即可查到每个学生对应的成绩,关联的列时ID列
# tables = students.merge(scores)    # 如果不设置连接的方式,则默认时内连接

# 要求把学生表的所有学生都显示出来,包括那些没有成绩的学生:用左连接 how="left"
tables = students.merge(scores,how="left",on="ID")

# 把没有匹配到的NaN 改为 0
# tables = students.merge(scores,how="left",on="ID").fillna("--")
tables = students.merge(scores,how="left",on="ID").fillna(0)

# 将成绩列的浮点类型改为整数型
tables = students.merge(scores,how="left",on="ID").fillna(0)
tables.Score = tables.Score.astype(int)

print(tables)

结果图:

技术分享图片

 

Pandas_两表联合(类似excel的vlookup操作)

原文:https://www.cnblogs.com/wodexk/p/10803979.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!