2017-06-30 166 views
2

我有两个数据框:填写基于来自大熊猫另一个数据帧相似的值在数据帧的列

df1        df2 
№ year      № year 
1 2010      373  
2 2010      374 
3 2010      375 
4 2010      376 
5 2010      ...     
... 
372 2017 
373 2017 
374 2017 
375 2017 
376 2017 
377 2017 
...       
899 2026 
900 2026 
901 2026 

我需要找到从DF2列“№”中的所有值的DF1,并填写df2中的列“year”与来自df1的值。 结果应该是这样的:

df2 
№ year 
373 2017 
374 2017 
375 2017 
376 2017 
... 

我试图做这样

df2['year'] = np.where(df2['№'] == df1['№'] , 'Insert value from df1['year'], '0') 

我第一次尝试插入“1”,而不是一年,以检查代码工作,它给了我这样一个错误

ValueError: Can only compare identically-labeled Series objects 

有什么建议吗?

回答

2

我觉得需要map通过Series通过set_index创建 - 如果某个值不匹配得到NaN S:

df2['year'] = df2['№'].map(df1.set_index('№')['year']) 

如果需要更换NaN s到原始值:

df2['year'] = df2['№'].map(df1.set_index('№')['year']).combine_first(df2['year']) 
+1

你也可以这样做:'df2 ['year'] = df1.set_index('№')['year'] [df2 ['№']]。值' – jdehesa

+0

@jdehesa - 是的,它也可以。但在我看来,地图更具有pandastic/pythonic。 – jezrael