Home > database >  Add a suffix column names in pandas data frame with repeated name
Add a suffix column names in pandas data frame with repeated name

Time:02-27

If I try to add a column df["x"] = ["d","e","f"] to this df:

     x    
0    a     
1    b     
2    c   

It will just override that df:

   x
0  d
1  e
2  f

But instead of replacing that column, how can pandas add a suffix in the column name if a duplicated column name is detected when i try to add a column? So the end result will be automatically:

   x_0  x_1
0  a    d
1  b    e
2  c    f

Thank you!

CodePudding user response:

def add_column(df, col, data):
    if col in df.columns:
        df[f'{col}_0'] = df[col]
        df[f'{col}_1'] = data
    else:
        df[col] = data

Create your own function and use it like this:

add_column(df, "x", ["d","e","f"])

CodePudding user response:

In your case you can try join

out = df.join(add, lsuffix = '_0',rsuffix='_1')
Out[361]: 
  x_0 x_1
0   a   d
1   b   e
2   c   f
#add = pd.DataFrame(["d","e","f"],columns=['x'])
  • Related