多索引系列中的自定义聚合

用户名

我该如何更换

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

按包含自定义聚合结果(例如

(3rd_entry-1st_entry)/ 1st_entry

对于每个一级索引组?

即,“ bar”的列值将是

(0.320251-0.791608)/0.791608

并且生成的系列应打印为

bar  -0.5954424412
baz  ...
foo  ...
BEN_YO

使用firstlast之后groupby,您也可以使用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

或者只是切片

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章