简体   繁体   English

将列添加到 Pandas 中的特定级别数据透视表

[英]add columns to specific level pivot tables in pandas

I am trying to achieve this multi-indexing form with a pandas pivot table.我正在尝试使用 Pandas 数据透视表来实现这种多索引形式。 在此处输入图片说明

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我用这个代码table = pd.pivot_table(df, index=str(df.columns[0]), columns =list(df.columns[1:4]), values='Value')得到这个结果

在此处输入图片说明

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.但是现在我需要将这三列(Forcast、Tolerance、Baseline Forcast)添加到每个子产品的数据透视表的最详细级别,就像在 ECo 下添加它们一样,我尝试了这个table[('OcP', 'CoC', 'tolerance')] = 0它起作用了,但像这样将列添加到数据透视表的末尾。

在此处输入图片说明

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.将 'OcP' 设置为 level1,将'CoC' 设置为 level2,将'tolerance' 设置为 level3。

You said you want them on level3 than you have to set them like this:你说你想要它们在 level3 而不是你必须像这样设置它们:

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)到枢轴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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