0

i have a dataframe like this

    Number  Names  
0   1       Josh   
1   2       Jon    
2   3       Adam   
3   4       Barsa  
4   5       Fekse  
5   6       Bravo  
6   7       Barsa 
7   8       Talyo  
8   9       Jon  
9   10      Zidane 

how can i group these numbers based on names

for Number,Names in zip(dsa['Number'],dsa['Names'])
print(Number,Names)

The above code gives me following output

1 Josh
2 Jon
3 Adam
4 Barsa
5 Fekse
6 Bravo
7 Barsa
8 Talyo
9 Jon
10 Zidane

How can i get a output like below

1 Josh
2,9 Jon
3 Adam
4,7 Barsa
5 Fekse
6 Bravo
8 Talyo
10 Zidane

I want to group the numbers based on names

foret
  • 337
  • 1
  • 5
  • 14
  • `df.groupby('Names').Number.apply(list)` should work, this is a duplicate question though. i'll find a better answer to link to. – Haleemur Ali Oct 13 '18 at 18:24
  • 1
    Possible duplicate of [grouping rows in list in pandas groupby](https://stackoverflow.com/questions/22219004/grouping-rows-in-list-in-pandas-groupby) – Haleemur Ali Oct 13 '18 at 18:26

3 Answers3

1

Something like this?

df.groupby("Names")["Number"].unique()

This will return you a series and then you can transform as you wish.

user3483203
  • 50,081
  • 9
  • 65
  • 94
shmit
  • 2,306
  • 2
  • 16
  • 20
0

Use pandas' groupby function with agg which aggregates columns. Assuming your dataframe is called df:

grouped_df = df.groupby(['Names']).agg({'Number' : ['unique']})

This is grouping by Names and within those groups reporting the unique values of Number.

T Burgis
  • 1,395
  • 7
  • 9
0

Lets say the DF is:

A = pd.DataFrame({'n':[1,2,3,4,5], 'name':['a','b','a','c','c']})

   n name
0  1    a
1  2    b
2  3    a
3  4    c
4  5    c

You can use groupby to group by name, and then apply 'list' to the n of those names:

A.groupby('name')['n'].apply(list)
name
a    [1, 3]
b       [2]
c    [4, 5]
Shahaf Finder
  • 604
  • 1
  • 4
  • 11