pandas join DataFrame force suffix?

后端 未结 4 1625
暖寄归人
暖寄归人 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:12

    You could force a suffix on the actual DataFrame:

    In [11]: df_a = pd.DataFrame([[1], [2]], columns=['A'])
    
    In [12]: df_b = pd.DataFrame([[3], [4]], columns=['B'])
    
    In [13]: df_a.join(df_b)
    Out[13]: 
       A  B
    0  1  3
    1  2  4
    

    By appending to it's column's names:

    In [14]: df_a.columns = df_a.columns.map(lambda x: str(x) + '_a')
    
    In [15]: df_a
    Out[15]: 
       A_a
    0    1
    1    2
    

    Now joins won't need the suffix correction, whether they collide or not:

    In [16]: df_b.columns = df_b.columns.map(lambda x: str(x) + '_b')
    
    In [17]: df_a.join(df_b)
    Out[17]: 
       A_a  B_b
    0    1    3
    1    2    4
    

提交回复
热议问题