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