How to combine dataframe rows, and combine their string column into list?

Viewed 98

Say I have a Pandas dataframe:

index  name      A
0      one       a
1      two       a
2      one       b
3      two       a

How can I merge rows with identical 'name' so that the new column A is a list of all the A associated with each 'name'? So, the output would be:

index  name      A
0      one       [a, b]
1      two       [a]
1 Answers

This will group by the name column and set all of the values in a to a unique list

import pandas as pd
import numpy as np

df.groupby(['name'])['A'].apply(lambda x : np.unique(list(x))).reset_index()
Related