将列添加到 pandas 中的特定级别数据透视表
add columns to specific level pivot tables in pandas
我正在尝试使用 pandas 枢轴 table 实现此 multi-indexing 形式。
因为原来的数据是这样的
我使用这段代码 table = pd.pivot_table(df, index=str(df.columns[0]), columns =list(df.columns[1:4]), values='Value')
得到了这个结果
但现在我需要将这三列(Forcast、Tolerance、Baseline Forcast)添加到每个子产品的最详细级别 table,例如将它们添加到 ECo 下,我试过这个 table[('OcP', 'CoC', 'tolerance')] = 0
它起作用了,但是像这样将列添加到数据透视表 table 的末尾。
那么如何添加它们并使它们落在已经存在的相同 sub-category 下,而不是像上图所示那样位于枢轴的末尾?
注意:我知道有类似的问题,但他们没有解决我的问题。
table[('OcP', 'CoC', 'tolerance')] = 0
将 'OcP' 设置为 level1 'CoC' 设置为 level2,将 'tolerance' 设置为 level3。
你说你想让它们在 level3 而不是你必须这样设置它们:
table[(level1, level2, "CoC")]
您还需要在层次结构中指定向上索引。
然后将新列添加到数据框的末尾,它看起来好像不是多索引层次结构的一部分,但它确实是,您可以通过调用 table 来检查这一点[(level1, level2)] 你会看到它包含在内。
如果您想按多索引层次结构排序显示它们,您应该对列进行排序:
df.iloc[:,df.columns.sortlevel(level=[0,1])[1]]
感谢 borut he lighted the way to it and this question,我终于找到了解决方案,它使用 table[('OcP', 'CoC', 'tolerance')] = 0
,然后将 pivot.sort_index(axis=1)
应用于枢轴。
我正在尝试使用 pandas 枢轴 table 实现此 multi-indexing 形式。
因为原来的数据是这样的
我使用这段代码 table = pd.pivot_table(df, index=str(df.columns[0]), columns =list(df.columns[1:4]), values='Value')
得到了这个结果
但现在我需要将这三列(Forcast、Tolerance、Baseline Forcast)添加到每个子产品的最详细级别 table,例如将它们添加到 ECo 下,我试过这个 table[('OcP', 'CoC', 'tolerance')] = 0
它起作用了,但是像这样将列添加到数据透视表 table 的末尾。
那么如何添加它们并使它们落在已经存在的相同 sub-category 下,而不是像上图所示那样位于枢轴的末尾? 注意:我知道有类似的问题,但他们没有解决我的问题。
table[('OcP', 'CoC', 'tolerance')] = 0
将 'OcP' 设置为 level1 'CoC' 设置为 level2,将 'tolerance' 设置为 level3。
你说你想让它们在 level3 而不是你必须这样设置它们:
table[(level1, level2, "CoC")]
您还需要在层次结构中指定向上索引。
然后将新列添加到数据框的末尾,它看起来好像不是多索引层次结构的一部分,但它确实是,您可以通过调用 table 来检查这一点[(level1, level2)] 你会看到它包含在内。
如果您想按多索引层次结构排序显示它们,您应该对列进行排序:
df.iloc[:,df.columns.sortlevel(level=[0,1])[1]]
感谢 borut he lighted the way to it and this question,我终于找到了解决方案,它使用 table[('OcP', 'CoC', 'tolerance')] = 0
,然后将 pivot.sort_index(axis=1)
应用于枢轴。