Python 熊猫:多对一

Python 熊猫:多对一,python,pandas,dataframe,merge,many-to-one,Python,Pandas,Dataframe,Merge,Many To One,假设我有两个数据帧: df1: Name Age Pete 19 John 30 Max 24 df2: Name Subject Grade Pete Math 90 Pete History 100 John English 90 Max History 90 Max Math 80 我想将它们合并为多对一的df2到df1,最终得到如下结果: Name Age Subject Grade Pete 19

假设我有两个数据帧:

df1

Name  Age
Pete  19
John  30
Max   24
df2

Name   Subject  Grade  
Pete   Math     90
Pete   History  100
John   English  90
Max    History  90
Max    Math     80
我想将它们合并为多对一的
df2
df1
,最终得到如下结果:

Name   Age  Subject  Grade  
Pete   19   Math     90
Pete   19   History  100
John   30   English  90
Max    24   History  90
Max    24   Math     80

我不想按
科目
等级
对它们进行分组,我需要复制它们,这样可以保留所有内容。

只需使用
pd。合并
,如下所示:

import pandas as pd
if __name__ == '__main__':
    df1 = pd.DataFrame({"Name": ["Pete", "John", "Max"],
                        "Age": [19, 30, 24]})
    df2 = pd.DataFrame({"Name": ["Pete", "Pete", "John", "Max", "Max"],
                        "Subject": ["Math", "History", "English", "History", "Math"],
                        "Grade": [90, 100, 90, 90, 80]})
    df3 = pd.merge(df1, df2, how="right", on="Name")
    print(df1)
    print(df2)
    print(df3)
结果:

   Name  Age
0  Pete   19
1  John   30
2   Max   24
   Name  Subject  Grade
0  Pete     Math     90
1  Pete  History    100
2  John  English     90
3   Max  History     90
4   Max     Math     80
   Name  Age  Subject  Grade
0  Pete   19     Math     90
1  Pete   19  History    100
2  John   30  English     90
3   Max   24  History     90
4   Max   24     Math     80
请阅读和介绍旅游。“告诉我如何解决这个编码问题”是。您需要做一个简单的测试,然后就您的实现提出一个具体的问题。