【问题标题】:How to create Pivot Table with Python Dataframe based on columns's substring values and counts?如何根据列的子字符串值和计数使用 Python Dataframe 创建数据透视表?
【发布时间】:2019-01-03 03:56:39
【问题描述】:

数据集:

Item_Identifier Item_Weight Item_Fat_Content Item_Visibility \ 0 FDA15 9.30 低脂 0.016047 1 DRC01 5.92 常规 0.019278 2 FDN15 17.50 低脂 0.016760 3 FDX07 19.20 常规 0.065953 4 NCD19 8.93 低脂 0.065953 Item_Type Item_MRP Outlet_Identifier \ 0 乳制品 249.8092 OUT049 1 软饮料 48.2692 OUT018 2 肉 141.6180 OUT049 3 水果和蔬菜 182.0950 OUT010 4户53.8614 OUT013 Outlet_Establishment_Year Outlet_Size Outlet_Location_Type \ 0 1999 中等等级 1 1 2009 年中 3 级 2 1999 年中 1 级 3 1998 中型 3 级 4 1987 年高级 3 Outlet_Type Item_Type_new 0 超市类型1 易腐烂 1超市类型2不易腐烂 2 超市 Type1 易腐烂 3 杂货店易腐烂 4 超市 Type1 不易腐烂

数据透视表:
索引:Item_Type,列:项目标识符的子字符串,值:计数。

预期输出:

博士 FD NC 烘焙食品 0 1086 0 面包 0 416 0 早餐 0 186 0 罐头 0 1084 0 乳制品 229 907 0 冷冻食品 0 1426 0 水果和蔬菜 0 2013 0 烈性饮料 362 0 0 健康与卫生 0 0 858 家庭 0 0 1548 肉类 0 736 0 其他 0 0 280 海鲜 0 89 0 零食 0 1989 0 软饮料 726 0 0 淀粉类食品 0 269 0

【问题讨论】:

  • 您的示例输出不清楚。你应该展示你试图给出一个更清晰的画面

标签: python python-3.x pandas dataframe


【解决方案1】:

创建一个新列,它是项 Item_Identifier 的子字符串。然后根据它们创建pivot_table。

这里是代码。 (假设 df 是带有数据集的数据框)

df['Item_Identifier_substr'] = df['Item_Identifier'].str.left(2)
pivot_df = df.pivot_table(index = 'Item_Type', columns = 'Item_Identifier_substr', values='Item_Identifier', aggfunc='count')

pivot_df

如果你喜欢,请给我的答案投票。

【讨论】:

    猜你喜欢
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 2017-10-21
    • 2020-12-23
    • 2018-12-02
    相关资源
    最近更新 更多