Skip to content

Instantly share code, notes, and snippets.

@evertrol
Last active January 20, 2016 04:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evertrol/12955a5d98edf055a2f4 to your computer and use it in GitHub Desktop.
Save evertrol/12955a5d98edf055a2f4 to your computer and use it in GitHub Desktop.
astropy.table.Table: aggregrate over & combine multiple columns
from astropy.table import Table
def average(col):
# Manipulate multiple columns at once?
return col.mean()
def average_pd(df):
weight = df['weight']
total = weight.sum()
df['value'] *= weight / total
df['value'] = df['value'].sum()
df['weight'] = total # for info; not necessary
return df.iloc[0] # ignore other rows: they are the same anyway
t = Table([['a', 'a', 'a', 'b', 'b', 'c'],
[1, 2, 3, 4, 5, 6],
[2, 2, 1, 2, 1, 1]],
names=('name', 'value', 'weight'))
print(t)
group = t.group_by('name')
result = group.groups.aggregate(average)
print(result)
df = t.to_pandas()
result = df.groupby('name')[['value', 'weight']].apply(average_pd)
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment