Concatenante multiple columns as string, to a new column

Viewed 61

I am trying to concatenate multiple columns as strings to a new one

Given the following example:

colA colB colC
0.4 2 test1
0.7 3 test2
0.8 4 test3

I need the new column

new column
colA0.4 colB2 colCtest1 colCtest1
colA0.7 colB3 colCtest2 colCtest2
colA0.8 colB4 colCtest3 colCtest3

And for instance, I would need to repeat certain columns just like column C

Initially I had the following function :

def create_soup(x):
    return ( ('colA' + str(x['colA']) + ' ') * 3
            
            + (str(x['colB']).replace(',', ' ') + ' ') * 2 )

and i applied like the following

df["soup"] = df.apply(create_soup, axis = 1)

But now I've tried with new ways such as

df['soup'] = df['colA'].apply(lambda x: f"colA{x}")

If you want to know why I can't use the previous function create_soup, it is because I have troubles implementing to my Python class, which is why i'm trying to find alternatives

Much thanks if you can provide any insights, or help

3 Answers

Change you lambda to this:

cols = ['colA', 'colB', 'colC']
df['new_col'] = df[cols].apply(lambda row: 'you can access row in this lambda.') # for examle row.colB

When you can vectorize your result - do so. Try to avoid using apply (as it goes on each row). For small dataset it makes no difference but when the dataframe is huge, you'll note a big difference in performance.

So a vectorize solution would be:

df['new column'] = 'colA'+df['colA'].astype(str)+' colB'+df['colB'].astype(str)+' colC'+df['colC'].astype(str)

You could use a list comprehension to get what you want:

df.assign(new_column = df.astype(str)
                         .assign(**{col : [f"{col}{entry}" 
                                           if col!="colC" 
                                           else f"{col}{entry} {col}{entry}" 
                                           for entry in df[col]] 
                                           for col in df})
                         .agg(" ".join, axis = "columns")
            )
    
   colA  colB   colC                         new_column
0   0.4     2  test1  colA0.4 colB2 colCtest1 colCtest1
1   0.7     3  test2  colA0.7 colB3 colCtest2 colCtest2
2   0.8     4  test3  colA0.8 colB4 colCtest3 colCtest3
Related