簡體   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