python-3.x - Pandas 中基于 groupby 的数据透视表
问题描述
我有一个这样的数据框:
customer_id | date | category
1 | 2017-2-1 | toys
2 | 2017-2-1 | food
1 | 2017-2-1 | drinks
3 | 2017-2-2 | computer
2 | 2017-2-1 | toys
1 | 2017-3-1 | food
>>> import pandas as pd
>>> dt = dict(customer_id=[1,2,1,3,2,1],
date='2017-2-1 2017-2-1 2017-2-1 2017-2-2 2017-2-1 2017-3-1'.split(),
category=["toys", "food", "drinks", "computer", "toys", "food"]))
>>> df = pd.DataFrame(dt)
使用我的新列和一个热编码这些列,我知道我可以使用df.pivot_table(index = ['customer_id'], columns = ['category'])
.
>>> df['Indicator'] = 1
>>> df.pivot_table(index=['customer_id'], columns=['category'],
values='Indicator').fillna(0).astype(int)
category computer drinks food toys
customer_id
1 0 1 1 1
2 0 0 1 1
3 1 0 0 0
>>>
我还想分组,date
所以每一行只包含来自同一日期的信息,就像在下面的所需输出中一样,id 1 有两行,因为date
列中有两个唯一的日期。
customer_id | toys | food | drinks | computer
1 | 1 | 0 | 1 | 0
1 | 0 | 1 | 0 | 0
2 | 1 | 1 | 0 | 0
3 | 0 | 0 | 0 | 1
解决方案
您可能正在寻找crosstab
>>> pd.crosstab([df.customer_id,df.date], df.category)
category computer drinks food toys
customer_id date
1 2017-2-1 0 1 0 1
2017-3-1 0 0 1 0
2 2017-2-1 0 0 1 1
3 2017-2-2 1 0 0 0
>>>
>>> pd.crosstab([df.customer_id,df.date],
df.category).reset_index(level=1)
category date computer drinks food toys
customer_id
1 2017-2-1 0 1 0 1
1 2017-3-1 0 0 1 0
2 2017-2-1 0 0 1 1
3 2017-2-2 1 0 0 0
>>>
>>> pd.crosstab([df.customer_id, df.date],
df.category).reset_index(level=1, drop=True)
category computer drinks food toys
customer_id
1 0 1 0 1
1 0 0 1 0
2 0 0 1 1
3 1 0 0 0
>>>
推荐阅读
- windows - 即使 SSH-Add 可以添加新密钥,OpenSSH 也无法提供密钥
- hbase - Apache Sqoop 从 Oracle 导入到 hbase 错误
- python - 空闲时python urwid超时
- flutter - Flutter:如何显示包含毫秒的时钟?
- html - Vue 2.x 过渡不适用于 Html 标签 ID CSS
- ansible - Ansible 加载 epel 和 yum 更新
- firebase - 使用全局 var/singleton 存储客户端发送的身份验证令牌?
- node.js - 通过 nodemailer 发送时未显示确认电子邮件的内容?
- ios - Flutter 找不到方法的原生 iOS 实现
- c# - 排序并打印 2 个元素的列表,而不将排序后的版本保存在另一个列表中