• 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)

    结果图:

  • 相关阅读:
    Celery(异步任务,定时任务,周期任务)
    SQLAlchemy的应用创建
    SQLAlchemy多对多
    SQLAlchemy
    app开发-2
    app开发-3
    app开发-1
    MongoDB-pymongo
    MongoDB-增删改查
    MongoDB-数据类型
  • 原文地址:https://www.cnblogs.com/wodexk/p/10803979.html
Copyright © 2020-2023  润新知