熊猫数据透视表将多行转置为列

时间:2019-11-24 14:57:21

标签: python pandas

我有一个这样的熊猫数据框:

+---------------+---------------------------+--------+
|     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'),并且可以获得一个数据框,该数据框的每个时间戳都是一个列,并且是电子邮件中的索引,但是我一直在理解如何创建所需的列。

1 个答案:

答案 0 :(得分:0)

使用:

#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)
相关问题