使用pandas重新排列表

2024-09-30 01:24:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张有客户ID和电子邮件的桌子。有些用户有多封电子邮件。该表如下所示:

| Customer  | Email          |
| ----------| -------------- |
| 1         | jdoe@mail.com  |
| 2         | jane1@mail.com |
| 3         | adam@mail.com  |
| 1         | john_d@mail.com|

我想做的是重新安排表,使每个客户ID只有一行,并将辅助电子邮件添加为附加列。大概是这样的:

| Customer  | Email1         |Email2         |
| ----------| -------------- |---------------|
| 1         | jdoe@mail.com  |john_d@mail.com
| 2         | jane1@mail.com |               |
| 3         | adam@mail.com  |               |

用熊猫做这个最好的方法是什么?我尝试过使用df.pivot,但这似乎对我不起作用


Tags: 用户comid客户电子邮件emailmailcustomer
2条回答

您可以使用cumcount创建多索引。然后使用unstack重新格式化数据,并通过add_prefix添加更改列名称:

    df = (df.set_index(['Customer',df.groupby('Customer').cumcount()])['Email']
        .unstack()
        .add_prefix('Email')
        .reset_index())
    print(df)

你会得到你想要的

您可以使用^{}+^{}+^{}

# We get the Customers with more than one email.
df_seconds_email = df[df['Customer'].duplicated()]

# We merge your original dataframe (I called it 'df') and the above one, suffixes param help us to get
# 'Email2' column, finally we drop duplicates taking into account 'Customer' column.
df = pd.merge(df, df_seconds_email, how='left', on=['Customer'], suffixes=('', '2')).drop_duplicates(subset='Customer')
print(df)

输出:

    Customer    Email          Email2
0      1    jdoe@mail.com   john_d@mail.com
1      2    jane1@mail.com      NaN
2      3    adam@mail.com       NaN

相关问题 更多 >

    热门问题