foret
foret

Reputation: 347

Grouping values in a a dataframe

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

Upvotes: 0

Views: 58

Answers (3)

shmit
shmit

Reputation: 2524

Something like this?

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

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

Upvotes: 1

Shahaf Finder
Shahaf Finder

Reputation: 674

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]

Upvotes: 0

T Burgis
T Burgis

Reputation: 1435

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.

Upvotes: 0

Related Questions