Add a pandas column that concatenates values in two other columns for the whole dataframe at once

38 Views Asked by At

I have a dataframe that looks like this:

   ColA  ColB
1   foo   xxx-123
2   goo   yyy-987

I want to add a column to the dataframe that puts the data together so that the dataframe looks like this:

    ColA  ColB     ColC
1   foo   xxx-123  foo (xxx-123)
2   goo   yyy-987  goo (yyy-987)

I have tried this, which I saw recommended as solutions in other similar situations:

df['ColC'] = df['ColA'] + ' (' + df['ColB'] + ')'

I was expecting to get this:

    ColA  ColB     ColC
1   foo   xxx-123  foo (xxx-123)
2   goo   yyy-987  goo (yyy-987)

Instead I got this error:

A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

I'd really rather not go row by row by row - does pandas have a way of doing this kind of thing like an Excel filldown?

1

There are 1 best solutions below

0
itprorh66 On

I don't know for sure this is what you want but here is an approach.

given your initial dataframe as df

df['ColC'] = zip(df['ColA'].to_list(), df['ColB'].to_list())  

Yields the following:

ColA    ColB    ColC
0   foo xxx-123 foo (xxx-123)
1   foo xxx-123 foo (xxx-123)