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

How to join rows in pandas dataframe based on column value?

I have a dataframe which looks like this:

time text
01.01.1970 abc
01.01.1970 cde
01.01.1970 fgh
01.01.1980 abc
01.01.1980 xyz

I would like to join the content in text based on column time. I want to join them separated by \n. How can I do this in order to get such a dataframe?

time text
01.01.1970 abc\ncde\nfgh
01.01.1980 abc\nxyz

I tried the following but I do not get what is expected but instead for every row in text I get: text\ntime.

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

out = (df.groupby('time', as_index=False)
       ['text'].agg(lambda x: '\n'.join(x.dropna())))

>Solution :

df.groupby('time')['text'].apply(lambda x: x.str.cat(sep='\n'))

output:

time    text
01.01.1970  "abc\ndef"
01.01.1980  "ghi\njkl"
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