【问题标题】:How to reshape multi index in a pandas dataframe like an excel pivot table如何像 excel 数据透视表一样重塑 pandas 数据框中的多索引
【发布时间】:2022-12-12 10:08:34
【问题描述】:

我有一个数据框,其中有 2 或 3 个级别的多重索引,我想将其重塑为 Excel 中的常用数据透视表,以便能够进行“内部”总计(参见图片)。

我尝试了 df.pivot_table() 和通过 .groupby() 的多重索引,但没有定论

我只有那个 DataFrame

这是代码

 df = pd.DataFrame({'Products': ['Products A','Products A', 
                           'Products A','Products B', 'Products B', 
                           'Products A', 'Products B', 'Products A'],

                   'Sub Products': ['Phone A','Phone B', 
                                   'Laptop B','Phone B', 'Laptop 
                                    B','Phone A','Phone B','Laptop A'],

                   'Color' : ['Green',  'Blue','Red',
                            'Red','Red','Blue','Green','Blue']})


df.groupby(['Products','Sub Products','Color' ]).count()

如果您有任何想法,那将非常有帮助! 谢谢。

【问题讨论】:

    标签: pandas pivot-table


    【解决方案1】:

    在 pandas 中,您通常不会将此聚合信息作为同一分组 DataFrame 的一部分包含在内,您可以在之后使用单独的命令获取它,例如:

    grand_total = df.sum()

    请注意,您在问题中提供的数据并不能完全产生图像中的数据。数字不同,一些 A/B 标签不一致。下面我编辑了您提供的代码,重现了与您的图像匹配的内容,假设您提供的示例数据的每一行都是一个“单元”。

    df = pd.DataFrame(
        {
            "Products": [
                "Products A",
                "Products A",
                "Products A",
                "Products B",
                "Products B",
                "Products A",
                "Products B",
                "Products A",
            ],
            "Sub Products": [
                "Phone A",
                "Phone A",
                "Laptop A",
                "Phone B",
                "Laptop  B",
                "Phone A",
                "Phone B",
                "Laptop A",
            ],
            "Color": ["Green", "Blue", "Red", "Red", "Red", "Blue", "Green", "Blue"],
        }
    )
    df['Count'] = 1
    df = df.groupby(['Products','Sub Products','Color' ]).sum()
    
    # To view the totals at any particular level of the multi-index
    display(df.groupby(level=0)['Count'].sum())
    display(df.groupby(level=1)['Count'].sum())
    display(df.groupby(level=2)['Count'].sum())
    

    我认为这提供了您想要的信息......但是从您的评论来看,听起来您只想要链接图像中显示的特定显示格式(多索引嵌套在单个列中)。据我所知,这不是 pandas DataFrames 中的一个选项。

    【讨论】:

    • 好的,非常感谢!
    • 你知道我如何将多索引合并到一个列而不是两个列中吗,真正困扰我的是我想计算电话 B 的数量,笔记本电脑 B 的数量,然后是产品 B 的数量。而且我必须将 df 导出到 excel,插入列,手动将 1 级索引移动到 0 级索引下。即使我得到 NaN,您是否有使用 Python 进行这种重塑的方法?
    猜你喜欢
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2021-05-12
    • 2019-12-07
    • 1970-01-01
    • 2021-01-16
    • 2016-09-15
    • 2017-05-24
    相关资源
    最近更新 更多