【发布时间】:2021-09-13 22:58:59
【问题描述】:
您好,我正在使用 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 等值
这是我正在使用的示例数据,下面是我尝试如何组织它。
谁能指导我如何解决这个问题?
样本数据:
| Name | Date | Items |
|---|---|---|
| johnny smith | 09/1/2021 | bread, oranges, peanut butter, apples, celery, peanuts |
| granny smith | 08/31/2021 | oranges, peanut butter, apples, bread |
| jane doe | 09/01/2021 | oranges, apples, celery, peanut butter |
| jack frost | 08/01/2021 | bread, oranges, apples |
| cinderella | 08/16/2021 | apples, peanuts, bread |
我想要达到的目标:
| Name | Date | Items0 | Items1 | Items2 | Items3 | Items4 | Items5 |
|---|---|---|---|---|---|---|---|
| johnny smith | 09/1/2021 | bread | oranges | peanut butter | apples | celery | peanuts |
| granny smith | 08/31/2021 | bread | oranges | peanut butter | apples | ||
| jane doe | 09/01/2021 | oranges | peanut butter | apples | |||
| jack frost | 08/01/2021 | bread | oranges | apples | |||
| cinderella | 08/16/2021 | bread | apples | peanuts |
【问题讨论】:
标签: python pandas pandas-groupby