Chetan P
Chetan P

Reputation: 187

groupby and function call in pandas

I have a dataframe where i have a column "Name". Name have multiples values like sample1, sample2, sample3. I want to apply a function to all those groups where value in Name column is same.

Output:

   Name  Value  Result
0  Name1      2       5
1  Name1      3       5
2  Name2      1      11
3  Name2      4      11
4  Name2      6      11
5  Name3      8      10
6  Name3      2      10

Upvotes: 5

Views: 2082

Answers (2)

id101112
id101112

Reputation: 1042

Df.groupby('Name').apply(lambda x: function (x.value))

The will work, in x.value you can put your column name

Upvotes: 0

johnpaton
johnpaton

Reputation: 765

Looks like you want a groupby.apply. Something like this should work:

import pandas as pd

df = # ... load your data

def group_sum(g):
    g["Result"] = g["Value"].sum()
    return g

df_grouped = df.groupby("Name").apply(group_sum)

Edit: Alexandre Nixon's answer is better for this use case.

Upvotes: 4

Related Questions