【问题标题】:Pandas Multiindex Series ProcessingPandas Multiindex 系列处理
【发布时间】:2019-01-07 09:11:09
【问题描述】:

我有一个 pandas 2 索引系列,是从 a.groupby() 我的原始 DataFrame 上获得的:

label  ncsc
False  0       297
       1       537
       2       333
       3       207
       4        51
       5        12
       6         4
       7         2
True   0        29
       1        68
       2        35
       3        29
       4        35
       5        18
       6         8
       7         2
Name: ncsc, dtype: int64

我希望能够为每个'ncsc' 计算真实率,即,对于 'ncsc'=6,真实率 = 8/(4+8) = 0.66。 您是否看到了一种不使用循环但使用“熊猫语法”的方法?

谢谢

【问题讨论】:

    标签: python pandas pandas-groupby multi-index


    【解决方案1】:

    假装你在处理数字:

    s[True] / (s[True] + s[False])
    #0    0.088957
    #1    0.112397
    #2    0.095109
    #3    0.122881
    #4    0.406977
    #5    0.600000
    #6    0.666667
    #7    0.500000
    

    【讨论】:

    • 绝对是最好的解决方案。熊猫索引真的很漂亮
    【解决方案2】:

    IIUC

    f = lambda s,v: s[s.index.get_level_values(0) == v].to_frame().reset_index('index', drop=True)
    
    tru = f(s, True)
    fal = f(s, False)
    (tru)/(tru+fal)
    
          ncsc
    label   
    0     0.088957
    1     0.112397
    2     0.095109
    3     0.122881
    4     0.406977
    5     0.600000
    6     0.666667
    7     0.500000
    

    【讨论】:

      猜你喜欢
      • 2019-11-27
      • 1970-01-01
      • 2012-10-13
      • 2018-02-02
      • 2020-05-19
      • 1970-01-01
      • 2017-04-06
      • 2018-07-25
      • 2015-06-13
      相关资源
      最近更新 更多