How do I join rows in pandas dataframe as new line in same row?

Viewed 83

I have a pandas dataframe that 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 rows of column text based on the entry for time. A new row should start in a new line.

The new dataframe should look like this:

time text
01.01.1970 abc
           cde
           fgh
01.01.1980 abc
           xyz

I tried this code:

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

But first: join by \n is not want I want. And secondly, the text column is just text\ntime. How can I modify my code or should I use another approach?

My question is related to this question: How can i use python to read output of linux program (top)

1 Answers

Check below code (updated as per OP comment below), this code will preserve order:

import pandas as pd

df = pd.DataFrame({'time':['01.01.1970','01.01.1970','01.01.1970','01.01.1980','01.01.1980'],'text':['cde','abc','fgh','abc','xyx']})


new_df = df.groupby(['time','text'], sort=False).agg({'text':'count'}).iloc[:,:-1]
new_df

Output:

enter image description here

Related