[英]Rearrange table using pandas
我有一张包含客户 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 但这似乎对我不起作用。
您可以使用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)
输出:
Customer Email Email2
0 1 jdoe@mail.com john_d@mail.com
1 2 jane1@mail.com NaN
2 3 adam@mail.com NaN
您可以使用cumcount
来创建 MultiIndex。 然后重塑通过使用数据unstack
通过,并添加改变列名add_prefix
:
df = (df.set_index(['Customer',df.groupby('Customer').cumcount()])['Email']
.unstack()
.add_prefix('Email')
.reset_index())
print(df)
你会得到你想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.