Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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  

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading