'Add a suffix column names in pandas data frame with repeated name
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!
Solution 1:[1]
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"])
Solution 2:[2]
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'])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Riccardo Bucco |
| Solution 2 | BENY |
