I have a table with customer IDs and emails. Some users have multiple emails. The table looks something like this:
| Customer | Email |
| ----------| -------------- |
| 1 | jdoe@mail.com |
| 2 | jane1@mail.com |
| 3 | adam@mail.com |
| 1 | john_d@mail.com|
What I would like to do is rearrange the table such that each customer ID has only one row and secondary emails are added as additional columns. Something like this:
| Customer | Email1 |Email2 |
| ----------| -------------- |---------------|
| 1 | jdoe@mail.com |john_d@mail.com
| 2 | jane1@mail.com | |
| 3 | adam@mail.com | |
What's the best way to do this using pandas? I have tried using df.pivot but that doesn't seem to be working for me.
You can use Series.duplicated()
+ pd.merge()
+ DataFrame.drop_duplicates()
# 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)
Output:
Customer Email Email2
0 1 jdoe@mail.com john_d@mail.com
1 2 jane1@mail.com NaN
2 3 adam@mail.com NaN
You can use cumcount
to create MultiIndex. Then reshape the data by using unstack
and add change columns names by add_prefix
:
df = (df.set_index(['Customer',df.groupby('Customer').cumcount()])['Email']
.unstack()
.add_prefix('Email')
.reset_index())
print(df)
And you'll get exactly what you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.