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 但这似乎对我不起作用。
解决方案
你可以使用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
推荐阅读
- r - 按日期和项目计数汇总
- css - 如何使表单标签(几乎)永远不会换行?
- qt - QCharts 右侧的第二个 Y 轴
- flutter - 当 2 个代码并排时出现颤振条码扫描问题
- c# - 如何从 Visual Studio 中找到 c# 项目的类型?
- java - 服务内的线程 - Android 应用程序
- pact - Pact JS - 如何发送请求正文以更改状态?
- javascript - 每次我在它们上放一个可拖动的表格时,表格都会改变行的高度
- javascript - 使用 jQuery 打开一个链接会打开相关的应用程序,但是,继续此操作,会打开一个烦人的 about:blank 页面。我怎样才能阻止这个?
- curl - curl 从命令行工作,但不能在 shell 脚本中工作(curl:(6)无法解析主机:)