【问题标题】:Custom aggregations in multiindex Series多索引系列中的自定义聚合
【发布时间】:2019-03-22 03:15:30
【问题描述】:

如何替换

中的列
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  ...

【问题讨论】:

    标签: python pandas


    【解决方案1】:

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

    【讨论】:

    • 切片方法不错。 +1
    猜你喜欢
    • 2018-03-30
    • 2023-01-30
    • 2022-12-16
    • 2020-01-02
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    相关资源
    最近更新 更多