我有以下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')]
只需使用
index matching
,因为您有具有相同标签的序列。你知道吗相关问题 更多 >
编程相关推荐