Dataframe using Pandas delimiting values using colon, commas and sorting

I have this DataFrame:

C0  C1   C2
0   jjj  3
0   aaa  2
1   bbb  7

What’s the most pythonic way of using Pandas to get this new DataFrame?

C0  C1  
0   aaa:2,jjj:3  
1   bbb:7  

>Solution :

You could sort the dataframe using DataFrame.sort_values. You can use Series.str.cat for concatenation with sep. Then groupby and use str.join.

df = df.sort_values('C1')
df["C1"].str.cat(df["C2"].astype(str), ":").groupby(df["C0"]).agg(
    ",".join
).to_frame().reset_index()

   C0           C1
0   0  aaa:2,jjj:3
1   1        bbb:7

Leave a Reply