scoffieldisxu
scoffieldisxu

Reputation: 85

How to aggregate text in pandas according to another column name

I want to aggregate the text column of all the identical names. e.g.

I have:

df = pd.DataFrame([['Tom', 'good', 3],
                   ['Jack', 'bad', 6],
                   ['Tom', 'average', 9],
                   ],
                  columns=['name', 'text', 'day'])

I want:

df = pd.DataFrame([['Tom', 'good average'],
                   ['Jack', 'bad',],
                   ],
                  columns=['name', 'text'])

Upvotes: 1

Views: 305

Answers (2)

scoffieldisxu
scoffieldisxu

Reputation: 85

df.groupby(by='name').agg(text=("text", lambda x: ",".join(set(x))))

Upvotes: 3

Kenan
Kenan

Reputation: 14104

Group by an join

df.groupby('name').agg({'text': ' '.join}, as_index=False)

              text
name
Jack           bad
Tom   good average

Upvotes: 2

Related Questions