Skip to content
Advertisement

Python Pandas: Append column value, based on another same column value

I have a pandas dataframe like this.

JavaScript

I want to append Town value, which is based on row have the same Source, Level and County value.

I have tried isin, groupby, diff(but my value is str), but still not figure out.

Image below is what I want to get.

JavaScript

Really appreciate your help!

Advertisement

Answer

The way we can make this work is by creating a list out of it using groupby() and apply(list), we can then transform this into a string separated by comma. Let’s split it into 2 steps for better understanding.

Personally I would keep this data as a list within a pandas series and not do step 2. Formatting as string separated by comma might not be ideal to work with.

Step 1:

JavaScript

Returns:

JavaScript

Now, we can format them correctly into strings (step 2):

JavaScript

Which outputs our desired result:

JavaScript
Advertisement