合并非唯一列 - 熊猫python

时间:2018-01-18 02:10:13

标签: python python-3.x pandas join merge

我一直在尝试将两个DataFrames合并在一起(dfdf_details),类似于Excel“vlookup”,但结果却很奇怪。下面我将展示两个DataFrames的结构,而不是为了简单而填充实际数据

df_details:

Abstract_Title  |  Abstract_URL  |  Session_No_v2  | Session_URL | Session_ID
  -------------------------------------------------------------------------
Abstract_Title1    Abstract_URL1         1          Session_URL1     12345
Abstract_Title2    Abstract_URL2         1          Session_URL1     12345
Abstract_Title3    Abstract_URL3         1          Session_URL1     12345
Abstract_Title4    Abstract_URL4         2          Session_URL2     22222 
Abstract_Title5    Abstract_URL5         2          Session_URL2     22222
Abstract_Title6    Abstract_URL6         3          Session_URL3     98765
Abstract_Title7    Abstract_URL7         3          Session_URL3     98765

df:

Session_Title   |   Session_URL   |   Sponsors   |    Type    |   Session_ID
    -------------------------------------------------------------------------------
Session_Title1     Session_URL1        x, y z     Paper             12345
Session_Title2     Session_URL2         x, y      Presentation      22222
Session_Title3     Session_URL3        a, b ,c    Presentation      98765
Session_Title4     Session_URL4          c        Talk              12121
Session_Title5     Session_URL5         a, x      Paper             33333

我希望合并Session_ID,我希望最终DataFrame看起来像: enter image description here

我已经尝试了以下脚本,它产生了一个DataFrame,它复制(几次)某些行并做了一些奇怪的事情。例如,df_details有7,046行,df有1,856行 - 当我运行以下合并代码时,我的final_df会产生21,148行:

final_df = pd.merge(df_details, df, how = 'outer', on = 'Session_ID')

请帮忙!

2 个答案:

答案 0 :(得分:1)

要生成最终输出表,我使用了以下代码:

final_df = pd.merge(df_details, df[['Session_ID',
                                'Session_Title',
                                'Sponsors',
                                'Type']], left_on = ['Session_ID'], right_on = ['Session_ID'], how = 'outer')

答案 1 :(得分:0)

使用“左”代替“外”。

final_df = pd.merge(df_details, df[['Session_ID','Session_Title','Sponsors','Type']], left_on = ['Session_ID'], right_on =['Session_ID'], how = 'left')
相关问题