如果值相同,Python Pandas将列从df复制到另一个 [英] Python Pandas copying column from df to another if values same

查看:368
本文介绍了如果值相同,Python Pandas将列从df复制到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据框:

DF ONE:

ID     A    B    C
 1     x    y    z
 1     x    y    z
 2     x    y    z
 2     x    y    z
 2     x    y    z
 3     x    y    z

DF 2:

ID     D    E    F
 1     a    b    c1
 2     a    b    c2
 3     a    b    c3

我想以DF TWO为例的列E,如果ID相同,则将其放在DF ONE上,因此我将得到以下输出:

I want to take column E for example from DF TWO, and put it on DF ONE, if the ID is the same, so after I will get this output:

ID     A    B    C    F
 1     x    y    z    c1
 1     x    y    z    c1
 2     x    y    z    c2
 2     x    y    z    c2
 2     x    y    z    c2
 3     x    y    z    c3

感谢您的帮助

推荐答案

您可以使用另一个解决方案是map by Series:

Another solution is map by Series:

s = df2.set_index('ID')['F']
print (s)
ID
1    c1
2    c2
3    c3
Name: F, dtype: object

df1['F'] = df1['ID'].map(s)
print (df1)
   ID  A  B  C   F
0   1  x  y  z  c1
1   1  x  y  z  c1
2   2  x  y  z  c2
3   2  x  y  z  c2
4   2  x  y  z  c2
5   3  x  y  z  c3

时间:

#[60000 rows x 5 columns]
df1 = pd.concat([df1]*10000).reset_index(drop=True)

In [115]: %timeit pd.merge(df1, df2[['ID', 'F']],how='left')
100 loops, best of 3: 11.1 ms per loop

In [116]: %timeit df1['ID'].map(df2.set_index('ID')['F'])
100 loops, best of 3: 3.18 ms per loop

In [117]: %timeit df1['ID'].map(df2.set_index('ID')['F'].to_dict())
100 loops, best of 3: 3.36 ms per loop

In [118]: %timeit df1['ID'].map({k:v for k, v in df2[['ID', 'F']].as_matrix()})
100 loops, best of 3: 3.44 ms per loop

In [119]: %%timeit 
     ...: df2.index = df2['ID']
     ...: df1['F1'] = df1['ID'].map(df2['F'])
     ...: 
100 loops, best of 3: 3.33 ms per loop

这篇关于如果值相同,Python Pandas将列从df复制到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆