参考多索引的pandas数据框架中的pandas系列值

2024-04-26 03:49:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下pandas.core.series.Series

Color
Red      4
Green    7

以及下面的多索引数据帧。我的目标是在数据帧中创建Target列,方法是将Value除以pandas.core.series.Series中相应的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')]

Tags: coretargetpandasindexvaluedtgreenred
1条回答
网友
1楼 · 发布于 2024-04-26 03:49:45

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

相关问题 更多 >