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


 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)

结果图:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM