Skip to content
Advertisement

Concatenate 3 or more column values into a single value, while maintaining dataframe in python

Data

type    id  count   date    name
set     A   AA01    Q4 21   hello
set     A   AA01    Q4 21   hello
set     A   AA01    Q4 21   hello
set     A   AA01    Q4 21   hello
no      B   BB01    Q4 21   hey

Desired

type    id  count   date    name      full
set     A   AA01    Q4 21   hello     A AA01 Q4 21 - hello
set     A   AA01    Q4 21   hello     A AA01 Q4 21 - hello
set     A   AA01    Q4 21   hello     A AA01 Q4 21 - hello
set     A   AA01    Q4 21   hello     A AA01 Q4 21 - hello
no      B   BB01    Q4 21   hey       B BB01 Q4 21 - hey

Doing

df['combined']=df['full'].astype(str)+'_'+df['id']+'_'+df['count']

However, the other columns are not being maintained. I am still troubleshooting, any suggestion is appreciated

Advertisement

Answer

df['full'] = df.apply(lambda row: str(row['id']) + ' ' + str(row['count']) + ' ' + str(row['date']) + ' - ' + str(row['name']), axis=1)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement