python - 熊猫数据透视表将多行转换为列
问题描述
我有一个结构如下的熊猫数据框:
+---------------+---------------------------+--------+
| Email | Paid at | Name |
+---------------+---------------------------+--------+
| john@mail.com | 2019-11-20 12:23:06 +0100 | #10710 |
| ed@mail.com | 2019-11-20 11:36:24 +0100 | #10709 |
| john@mail.com | 2019-11-19 14:58:41 +0100 | #10700 |
| ed@mail.com | 2019-11-19 14:41:30 +0100 | #10699 |
| dev@mail.com | 2019-11-19 14:20:26 +0100 | #10697 |
+---------------+---------------------------+--------+
我的最终目标是汇总一个用户进行的所有交易,格式如下:
+---------------+---------------------------+--------+---------------------------+--------+--+
| Email | Paid at | Name | Paid at | Name | |
+---------------+---------------------------+--------+---------------------------+--------+--+
| john@mail.com | 2019-11-20 12:23:06 +0100 | #10710 | 2019-11-19 14:58:41 +0100 | #10700 | |
| ed@mail.com | 2019-11-20 11:36:24 +0100 | #10709 | 2019-11-19 14:41:30 +0100 | #10699 | |
| dev@mail.com | 2019-11-19 14:20:26 +0100 | #10697 | | | |
+---------------+---------------------------+--------+---------------------------+--------+--+
我的起始数据框是这样构造的:
df = pd.DataFrame({'Email':['john@mail.com', 'ed@mail.com',
'john@mail.com', 'ed@mail.com', 'dev@mail.com'],
'Paid at':['2019-11-20 12:23:06 +0100',
'2019-11-20 11:36:24 +0100',
'2019-11-19 14:58:41 +0100',
'2019-11-19 14:41:30 +0100',
'2019-11-19 14:20:26 +0100'],
'Name':['#10710', '#10709', '#10700', '#10699', '#10697']})
我尝试使用数据透视函数df.pivot(index='Email', columns='Name', values='Paid at')
,我可以获得一个数据框,其中每个时间戳都是一个列和电子邮件中的索引,但我一直在理解如何创建我想要的列。
解决方案
利用:
#convert column to datetimes
df['Paid at'] = pd.to_datetime(df['Paid at'])
#descending sorting by datetimes
df = df.sort_values('Paid at', ascending=False)
#create MultiIndex by counter with cumcount, reshape by unstack, change order of columns
df = (df.set_index(['Email', df.groupby('Email', sort=False).cumcount()])
.unstack()
.sort_index(axis=1, level=[1,0], ascending=[True, False]))
#flatten MultIndex in columns
df.columns = df.columns.map('{0[0]}_{0[1]}'.format)
#convert index to column
df = df.reset_index()
print (df)
推荐阅读
- php - 无法连接 QuickBooks PHP DevKit
- vba - Microsoft Word 句子长度检查器
- c - 逐行存储文件的函数给出了奇怪的结果
- java - 获取真正的类类型
- python - Python/Selenium 组合多个列表并通过可见文本显示
- python-3.x - 导入错误:没有名为“scipy._lib”的模块
- sql - SQL Query - 类似的查询,执行时间差别很大
- tensorflow - 为什么 tflearn 预测模型的准确率不同。当在不同系统上训练相同的数据(训练数据)?
- angular - 如何从提供 HTTP 响应的服务器获取 HTTPS 响应
- java - Java流拆分行并存储在不同的对象中