我有一个三级多义度列Name, Period, Measurement
在我的玩具示例中,对于三个不同的人,我在两个时间段之前和之后的体重和身高。
我想生成一个数据帧,该数据帧在weight
期间显示三个名称中每个名称的height
除以before
。
我怀疑我使用level=
参数时犯了某种错误(或者也许。但是,无论我如何尝试,我都会得到TypeError: Join on level between two MultiIndex objects is ambiguous
我想了解如何控制操作,以便我可以指定“按名称显示给我,其中period ='before',重量除以身高”,以及更笼统的“按名称显示给我,并按期间,体重除以身高“
arrays = [['mike', 'mike', 'mike', 'mike','matt', 'matt', 'matt', 'matt','dave','dave', 'dave','dave', ],
['before', 'before', 'after', 'after']*3,
['height', 'weight']*6]
cols = pd.MultiIndex.from_arrays(arrays, names=('name', 'period', 'statistic'), )
the_data = [[1.8, 200, 1.7,170]*3,[1.8, 190, 1.7,166]*3 ]
idx = pd.IndexSlice
xf = pd.DataFrame(index=pd.date_range(start="20191201", periods=2, freq="d"),
data=the_data, columns=cols)
xf.loc[:, idx[:,'before','weight']].divide(xf.loc[:, idx[:,'before','height']], level=[0], axis='columns')
您快到了。刚刚在分区中错过了values
:
print(xf.loc[:, idx[:,'before','weight']].divide(xf.loc[:, idx[:,'before','height']].values, level=[0], axis='columns'))
结果:
name mike matt dave
period before before before
statistic weight weight weight
2019-12-01 111.111111 111.111111 111.111111
2019-12-02 105.555556 105.555556 105.555556
为了正确对齐,必须具有相同的MultiIndex值,因此您可以在此处使用rename
:
print (xf.loc[:, idx[:,'before','weight']].divide(xf.loc[:, idx[:,'before','height']].rename(columns={'height':'weight'})))
name mike matt dave
period before before before
statistic weight weight weight
2019-12-01 111.111111 111.111111 111.111111
2019-12-02 105.555556 105.555556 105.555556