Last active
January 20, 2016 04:48
-
-
Save evertrol/12955a5d98edf055a2f4 to your computer and use it in GitHub Desktop.
astropy.table.Table: aggregrate over & combine multiple columns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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