简体   繁体   中英

add columns to specific level pivot tables in pandas

I am trying to achieve this multi-indexing form with a pandas pivot table. 在此处输入图片说明

since the original data were like this.

在此处输入图片说明

I used this code table = pd.pivot_table(df, index=str(df.columns[0]), columns =list(df.columns[1:4]), values='Value') to get this result

在此处输入图片说明

but now I need to add these three columns (Forcast, Tolerance, Baseline Forcast) to the most detailed level of the pivot table for each subproduct like adding them under the ECo, I tried this table[('OcP', 'CoC', 'tolerance')] = 0 it worked but added the column to the end of the pivot table like this.

在此处输入图片说明

so how can add them and make them fall under the same sub-category that is already existed not at the end of the pivot like shown above? Note: I know there are similar questions but they didn't solve my case.

table[('OcP', 'CoC', 'tolerance')] = 0

Sets 'OcP' as level1 'CoC' as level2 and 'tolerance' as level3.

You said you want them on level3 than you have to set them like this:

table[(level1, level2, "CoC")]

You need to specify the index up in the hierarchy as well.

多亏了borut,我终于找到了解决方案,他为它指明了方向,这个问题是使用table[('OcP', 'CoC', 'tolerance')] = 0然后应用pivot.sort_index(axis=1)到枢轴。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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