【问题标题】:Merge and Format in PandasPandas 中的合并和格式化
【发布时间】:2018-02-09 19:09:41
【问题描述】:

所以我正在学习 Pandas,但在合并两个数据帧时遇到问题。可能更多的是格式问题,但即使经过大量尝试研究,我也没有得到它。

假设我们有两节数学辅导课,我们想知道哪些学生参加了这两个课。

数据框 A。

Id Subject Students_A 1 Maths Ron 2 Maths Harry 3 Maths Hermionie 4 Maths Draco

数据框 B。

Id Subject Students_B 1 Maths Harry 2 Maths Draco 3 Maths Neville

现在我在 jupyter notebook 中做了这个:

df_common = pd.merge(df_A,df_B,left_on='studentA', right_on='studentB', how='outer')

得到了这个:

Id Subject_x StudentA Subject_y StudentB 1 Maths Ron Nan Nan 2 Maths Harry Maths Harry 3 Maths Hermionie Nan Nan 4 Maths Draco Maths Draco 5 Nan Nan Maths Neville

但是我想要这样的东西:

Id Subject StudentA StudentB 1 Maths Ron Nan 2 Maths Harry Harry 3 Maths Hermionie Nan 4 Maths Draco Draco 5 Maths Nan Neville

我做错了什么?谢谢!

【问题讨论】:

    标签: python pandas numpy jupyter-notebook


    【解决方案1】:

    合并StudentsSubject

    df1.merge(df2, how="outer",
                   left_on=["Subject","Students_A"], 
                   right_on=["Subject","Students_B"])
    
      Subject Students_A Students_B
    0   Maths        Ron        NaN
    1   Maths      Harry      Harry
    2   Maths  Hermionie        NaN
    3   Maths      Draco      Draco
    4   Maths        NaN    Neville
    

    注意:假设Id 可以用作索引,例如

    df1 = pd.read_clipboard(index_col="Id")
    
       Subject Students_A
    Id                   
    1    Maths        Ron
    2    Maths      Harry
    3    Maths  Hermionie
    4    Maths      Draco
    

    【讨论】:

      【解决方案2】:

      在合并语句之后试试这个:

      df_common["Subject"] = df_common["Subject_x"].fillna(df_common["Subject_y"])
      df_common = df_common.drop(["Subject_x", "Subject_y"], 1)
      

      所以基本上当您执行连接时,Subject 被重命名为 Subject_x 和 Subject_y 以便您可以区分它们。为了连接这些列,创建一个名为 Subject 的新列,它接受 Subject_x 中的非 Null 值,其中 Null 从 Subject_y 中提取值。然后删除 Subject_x 和 Subject_y

      【讨论】:

      • df_common.drop(["Subject_x", "Subject_y"],axis=1)
      • 啊,我怎么没想到呢。我以为我们可以通过合并语句来做到这一点。
      猜你喜欢
      • 1970-01-01
      • 2010-10-17
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      • 2021-12-15
      • 2019-11-30
      • 1970-01-01
      相关资源
      最近更新 更多