2
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.

Nick
  • 138,499
  • 22
  • 57
  • 95
Aadhi Verma
  • 172
  • 2
  • 11

2 Answers2

4

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]
Nick
  • 138,499
  • 22
  • 57
  • 95
1

You can use groupby(), apply() and reset_index():

df = df.groupby("id")['name'].apply(list).reset_index()

df:

  id       name
0  A  [1, 2, 3]
1  B  [4, 5, 6]
2  C        [7]

Additionally, if you want the name column to be a string instead of a list, you can do the following:

df = df.groupby("id")['name'].apply(list).apply(lambda x: ",".join(str(i) for i in x)).reset_index()

df:

  id   name
0  A  1,2,3
1  B  4,5,6
2  C      7
Marcelo Paco
  • 2,732
  • 4
  • 9
  • 26