Pandas Merge - How to avoid duplicating columns

前端 未结 5 1422
轮回少年
轮回少年 2020-11-28 02:23

I am attempting a merge between two data frames. Each data frame has two index levels (date, cusip). In the columns, some columns match between the two (currency, adj date

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 02:54

    Building on @rprog's answer, you can combine the various pieces of the suffix & filter step into one line using a negative regex:

    dfNew = df.merge(df2, left_index=True, right_index=True,
                 how='outer', suffixes=('', '_DROP')).filter(regex='^(?!.*_DROP)')
    

    Or using df.join:

    dfNew = df.join(df2, lsuffix="DROP").filter(regex="^(?!.*DROP)")
    

    The regex here is keeping anything that does not end with the word "DROP", so just make sure to use a suffix that doesn't appear among the columns already.

提交回复
热议问题