编程语言
首页 > 编程语言> > python – 合并两个数据帧而不重复pandas

python – 合并两个数据帧而不重复pandas

作者:互联网

我正在尝试合并两个数据框,一个包含列:customerId,全名和电子邮件,另一个数据框包含列:customerId,amount和date.我想让第一个数据帧成为主数据帧,并包含其他数据帧信息,但仅限于customerIds匹配时;我试过做:

 merge = pd.merge(df, df2, on='customerId', how='left')

但是生成的数据框包含大量重复并且看起来不对:

customerId  full name   emails  amount  date
0   002963338   Star shine  star.shine@cdw.com  $2,910.94   2016-06-14
1   002963338   Star shine  star.shine@cdw.com  $9,067.70   2016-05-27
2   002963338   Star shine  star.shine@cdw.com  $6,507.24   2016-04-12
3   002963338   Star shine  star.shine@cdw.com  $1,457.99   2016-02-24
4   986423367   palm tree   tree.palm@snapchat.com,tree@.com    $4,604.83   2016-07-16

这不行,请帮忙!

解决方法:

在customerId列中存在重复的问题.

因此解决方案是删除它们,例如到drop_duplicates

df2 = df2.drop_duplicates('customerId')

样品:

df = pd.DataFrame({'customerId':[1,2,1,1,2], 'full name':list('abcde')})
print (df)
   customerId full name
0           1         a
1           2         b
2           1         c
3           1         d
4           2         e

df2 = pd.DataFrame({'customerId':[1,2,1,2,1,1], 'full name':list('ABCDEF')})
print (df2)
   customerId full name
0           1         A
1           2         B
2           1         C
3           2         D
4           1         E
5           1         F
merge = pd.merge(df, df2, on='customerId', how='left')
print (merge)
    customerId full name_x full name_y
0            1           a           A
1            1           a           C
2            1           a           E
3            1           a           F
4            2           b           B
5            2           b           D
6            1           c           A
7            1           c           C
8            1           c           E
9            1           c           F
10           1           d           A
11           1           d           C
12           1           d           E
13           1           d           F
14           2           e           B
15           2           e           D

df2 = df2.drop_duplicates('customerId')
merge = pd.merge(df, df2, on='customerId', how='left')
print (merge)
   customerId full name_x full name_y
0           1           a           A
1           2           b           B
2           1           c           A
3           1           d           A
4           2           e           B

标签:python,pandas,ipython,ipython-notebook,merge
来源: https://codeday.me/bug/20191002/1845206.html