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)

结果图:

猜你喜欢

转载自www.cnblogs.com/wodexk/p/10803979.html
今日推荐