Skip to content
Advertisement

Make list after groupby in pandas using apply() function

I have this dataframe:

    c1  c2  
0   B   1   
1   A   2   
2   B   5
3   A   3
4   A   7

My goal is to keep tracking the values in column2, based on the letters of column1 separated by(:), the output should look like this:

    c1  list
0   A   2:3:7   
1   B   1:5 


What’s the most pythonic way to do this:

At the moment I’m able to group by the column 1 and I’m trying to use the apply() function, but I do not know how to map and make this list in the new column.

Advertisement

Answer

Try this:

df = df.groupby("c1")["c2"].apply(lambda x: ":".join([str(i) for i in x])).reset_index()

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement