pandas join DataFrame force suffix?

后端 未结 4 1573
暖寄归人
暖寄归人 2021-02-05 02:32

How can I force a suffix on a merge or join. I understand it\'s possible to provide one if there is a collision but in my case I\'m merging df1 with df2 which doesn\'t cause an

4条回答
  •  别跟我提以往
    2021-02-05 03:21

    This is what I've been using to pandas.merge two DataFrames and force suffixing:

    def merge_force_suffix(left, right, **kwargs):
        on_col = kwargs['on']
        suffix_tupple = kwargs['suffixes']
    
        def suffix_col(col, suffix):
            if col != on_col:
                return str(col) + suffix
            else:
                return col
    
        left_suffixed = left.rename(columns=lambda x: suffix_col(x, suffix_tupple[0]))
        right_suffixed = right.rename(columns=lambda x: suffix_col(x, suffix_tupple[1]))
        del kwargs['suffixes']
        return pd.merge(left_suffixed, right_suffixed, **kwargs)
    

提交回复
热议问题