代码之家  ›  专栏  ›  技术社区  ›  gibbz00

引用多索引数据帧中的熊猫系列值

  •  1
  • gibbz00  · 技术社区  · 8 年前

    我有以下几点 pandas.core.series.Series :

    Color
    Red      4
    Green    7
    

    Target Value 通过相应的 Color . 例如,第一行目标应该是12/4=3。

                  Value    Target
    Color Animal       
    Red   Tiger      12      3
          Tiger      24      6
    Green Lion       21      3
          Lion       35      5
    

    我下面的尝试在使用单索引时效果很好,但在使用多索引时失败,出现错误 Index._join_level on non-unique index is not implemented

    import pandas as pd
    x = pd.Series([4,7], index=['Red','Green'])
    x.index.name = 'Color'
    
    dt = pd.DataFrame({'Color': ['Red','Red','Green','Green'], 'Animal': ['Tiger','Tiger','Lion','Lion'],  'Value': [12,24,21,35]})
    dt.set_index(['Color','Animal'], inplace=True)
    dt['Target'] = dt['Value'] / x.loc[dt.index.get_level_values('Color')]
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   rafaelc    8 年前

    简单使用 index matching

    dt['Target'] = dt.Value/x
    
                    Value   Target
    Color   Animal      
    Red     Tiger   12      3.0
            Tiger   24      6.0
    Green   Lion    21      3.0
            Lion    35      5.0