import pandas as pd
df = pd.DataFrame({'id':['A','A','A','B','B','B','C'],'name':[1,2,3,4,5,6,7]})
print(df.to_string(index=False))
As of now the output for above code is:
id name
A 1
A 2
A 3
B 4
B 5
B 6
C 7
But I am expeting its output like:
id name
A 1,2,3
B 4,5,6
C 7
I ain’t sure how to do it, I have tried several other codes but didn’t work for me. Please help in solving this.
>Solution :
If you want a comma separated list of values, you can aggregate using join, noting that you have to convert the values to strings first:
df2 = df.groupby('id', as_index=False).agg(lambda x: ','.join(map(str, x)))
print(df2.to_string(index=False))
Output:
id name
A 1,2,3
B 4,5,6
C 7
If you just want a list of values, aggregate using list:
df2 = df.groupby('id', as_index=False).agg(list)
print(df2.to_string(index=False))
Output:
id name
A [1, 2, 3]
B [4, 5, 6]
C [7]