python - 在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 日 | 面包 | 苹果 | 花生 |
解决方案
一种方法是从字符串中获取分类值,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_dummies
将Item
列转换为分类值:
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
.
推荐阅读
- ios - WKWebView 正在尝试在后台运行,尽管它已关闭并且应该被处置
- python - psycopg2:如何将数据从 Python 应用程序添加到 Postgresql
- java - 为什么 saveAll() 总是插入数据而不是更新数据?
- arrays - 读取浮点数的二进制文件并将它们放入数组中
- amazon-web-services - 为什么我的 AWS S3 策略不会仅限制某些 IP 地址的访问?
- python - mplfinance 图未正确显示时间值
- reactjs - 在reactjs nextjs中将url重定向到www作为服务器端301
- python - 在 Python 中调用变量(本地与全局)
- c# - 如何在控制器中使用 IdentityServer4 获取 ASP.NET 核心中的当前用户?
- r - 在 R 中使用 plot_grid 和 get_legend 的困难