首页 > 解决方案 > 在python中对列进行分组

问题描述

您好,我正在使用 python 处理 .csv 中的数据集,并且在对列进行分组时遇到错误。我正在使用的代码是:

import pandas as pd 
df=pd.read_excel('filepath')
df['Items'].str.split(',', expand=True)
df=df.groupby(['Items0', 'Items1','Items2', 'Items3', 'Items4', 'Items5' ]).size()
print(df)

当我运行 print(df) 时,我得到诸如 Items0-1、Items1-1、Items2-1 等值

这是我正在使用的示例数据,我正在尝试如何组织它。

有人可以指导我如何解决这个问题吗?

样本数据:

姓名 日期 项目
约翰尼史密斯 2021 年 9 月 1 日 面包、橘子、花生酱、苹果、芹菜、花生
史密斯奶奶 2021 年 8 月 31 日 橘子、花生酱、苹果、面包
简·多伊 2021 年 9 月 1 日 橘子、苹果、芹菜、花生酱
杰克弗罗斯特 2021 年 8 月 1 日 面包,橘子,苹果
灰姑娘 2021 年 8 月 16 日 苹果、花生、面包

我试图实现的目标:

姓名 日期 项目0 项目1 项目2 项目3 项目4 项目5
约翰尼史密斯 2021 年 9 月 1 日 面包 橘子 花生酱 苹果 芹菜 花生
史密斯奶奶 2021 年 8 月 31 日 面包 橘子 花生酱 苹果
简·多伊 2021 年 9 月 1 日 橘子 花生酱 苹果
杰克弗罗斯特 2021 年 8 月 1 日 面包 橘子 苹果
灰姑娘 2021 年 8 月 16 日 面包 苹果 花生

标签: pythonpandaspandas-groupby

解决方案


一种方法是从字符串中获取分类值,Items然后重新格式化 DataFrame 并join重新组合在一起:

x = df.pop('Items').str.get_dummies(', ')
df = df.join(
    x.mul(x.columns).set_axis(
        range(len(x.columns)), axis=1
    ).add_prefix('Item')
)
           Name        Date   Item0  Item1   Item2    Item3          Item4    Item5
0  johnny smith   09/1/2021  apples  bread  celery  oranges  peanut butter  peanuts
1  granny smith  08/31/2021  apples  bread          oranges  peanut butter         
2      jane doe  09/01/2021  apples         celery  oranges  peanut butter         
3    jack frost  08/01/2021  apples  bread          oranges                        
4    cinderella  08/16/2021  apples  bread                                  peanuts

说明:用于str.get_dummiesItem列转换为分类值:

x = df.pop('Items').str.get_dummies(', ')
   apples  bread  celery  oranges  peanut butter  peanuts
0       1      1       1        1              1        1
1       1      1       0        1              1        0
2       1      0       1        1              1        0
3       1      1       0        1              0        0
4       1      1       0        0              0        1

这可以mul通过列名(将 1 值替换为列名)转换为所需的格式,set_axis以枚举列(0-项目数)和add_prefix“项目”到新编号的列:

x.mul(x.columns).set_axis(
    range(len(x.columns)), axis=1
).add_prefix('Item')

x

    Item0  Item1   Item2    Item3          Item4    Item5
0  apples  bread  celery  oranges  peanut butter  peanuts
1  apples  bread          oranges  peanut butter         
2  apples         celery  oranges  peanut butter         
3  apples  bread          oranges                        
4  apples  bread                                  peanuts

然后join回到df.


推荐阅读