Oblomov
Oblomov

Reputation: 9635

Custom aggregations in multiindex Series

How can I replace the column in

import numpy as np
import pandas as pd
arrays = [np.array(['bar', 'bar', 'bar','baz', 'baz','baz', 'foo', 'foo','foo']),
          np.array(['one', 'two', 'three', 'one', 'two','three', 'one', 'two','three'])]
s = pd.Series(np.random.randn(9), index=arrays)
print(s)

bar  one      0.791608
     two     -0.966179
     three    0.320251
baz  one      0.043479
     two     -1.637586
     three   -1.133128
foo  one     -0.575991
     two     -1.080433
     three    0.946663

by a column containing the results of a custom aggregation such as

(3rd_entry-1st_entry)/1st_entry

for each first level index group?

I.e., the column value for "bar" would be the result of

(0.320251-0.791608)/0.791608

and the resulting Series should print like

bar  -0.5954424412
baz  ...
foo  ...

Upvotes: 0

Views: 31

Answers (1)

BENY
BENY

Reputation: 323306

Using first and last after groupby , also you can check with nth

g=s.groupby(level=0)
(g.last()-g.first())/g.first()
Out[132]: 
bar   -0.818922
baz   -0.150440
foo    0.266949
dtype: float64

Or just slice

(s.loc[:,'three']-
   s.loc[:,'one'])/s.loc[:,'one']
Out[135]: 
bar   -0.818922
baz   -0.150440
foo    0.266949
dtype: float64

Upvotes: 1

Related Questions