繁体   English   中英

从多索引熊猫数据框中引用熊猫系列值

[英]Refer to a pandas series value from a multi-index pandas dataframe

我有以下pandas.core.series.Series

Color
Red      4
Green    7

和以下多索引数据框。 我的目标是通过将pandas.core.series.Series中的Value除以相应的Color值来在数据pandas.core.series.Series创建Target列。 例如,第一行目标应为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')]

只需使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM