Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas group by a specific value in any of given columns

Tags:

Given the pandas dataframe as follows:

   Partner1 Partner2    Interactions
0  Ann      Alice       1
1  Alice    Kate        8
2  Kate     Tony        9
3  Tony     Ann         2

How can I group by a specific partner, let's say to find the total number of interactions of Ann?

Something like

gb = df.groupby(['Partner1'] or ['Partner2']).agg({'Interactions': 'sum'})

and getting the answer:

Partner Interactions
Ann     3
Alice   9
Kate    17
Tony    11
like image 326
nons3rviam Avatar asked Sep 11 '20 09:09

nons3rviam


People also ask

How do you group data based on a column in Python?

groupby() function is used to split the data into groups based on some criteria. pandas objects can be split on any of their axes. The abstract definition of grouping is to provide a mapping of labels to group names.

How do I group values in a column in pandas?

Groupby is a very powerful pandas method. You can group by one column and count the values of another column per this column value using value_counts. Using groupby and value_counts we can count the number of activities each person did.


1 Answers

You can use melt together with groupby. First melt:

df = pd.melt(df, id_vars='Interactions', value_vars=['Partner1', 'Partner2'], value_name='Partner')

This will give:

   Interactions   variable  Partner
0             1   Partner1      Ann
1             8   Partner1    Alice
2             9   Partner1     Kate
3             2   Partner1     Tony
4             1   Partner2    Alice
5             8   Partner2     Kate
6             9   Partner2     Tony
7             2   Partner2      Ann

Now, group by Partner and sum:

df.groupby('Partner')[['Interactions']].sum()

Result:

Partner  Interactions
  Alice             9
    Ann             3
   Kate            17
   Tony            11
like image 136
Shaido Avatar answered Sep 21 '22 14:09

Shaido