• Home
  • Django
  • Pandas groupby custom function and apply function

Pandas groupby custom function and apply function

linkaiyi
Follow

result of pandas groupby is a list of dataframe objects by grouped columns. Use x to define custom apply function

def concat_string(x):
    x['City'] = ','.join(set(x['City']))
    return x.iloc[0]

    df_orig.groupby('Province').apply(concat_string).to_csv('c:\\test.csv')

resulting to join City column together of the same Province

from pandas import *

d = {"my_label": Series(['A','B','A','C','D','D','E'])}
df = DataFrame(d)


def as_perc(value, total):
    return value/float(total)

def get_count(values):
    return len(values)

grouped_count = df.groupby("my_label").my_label.agg(get_count)
data = grouped_count.apply(as_perc, total=df.my_label.count())

The .agg() method here takes a function that is applied to all values of the groupby object.

def my_cool_func(x):
    #print (x)
    return (x.max() - x.min()) / 2

df3=df1.groupby(['Country'])['Revenue'].apply(my_cool_func).reset_index()
print (df3)
  Country  Revenue
0  Canada    150.0
1      US    100.0
import pandas as pd

df = pd.DataFrame({'foo': [1, 2, 3], 'bar': ['a', 'b', 'c'], 'baz': [0, 0, 1]})

def calc_qux(x):

    return ','.join(x['foo'].astype(str).values) + ''.join(x['bar'].values)

df.groupby('baz').apply(calc_qux).to_frame('qux')
Object has 0 attachments

Was this article helpful?

This article is viewed 10 times!

0 Comments

Leave a Comment

Support