从其他数据帧pandas填充数据框中列的NAN值

时间:2016-12-07 06:29:58

标签: python pandas

我在pandas df中有一张桌子

      main_id       p_id_y       score
1       1            123        0.617523
0       2            456        0.617523
0       3            789        NaN
0       4            987        NaN
1       5            654        NaN

我还有另一个数据帧df2。 其中有专栏

p_id   score
 123    1.3
 456    4.6
 789    0.4
 987    1.1
 654    3.2

我必须填写所有p_id_y which is NaN的所有分数,p_id分别为df2

我的最终输出应该是。

      main_id       p_id_y       score
1       1            123        0.617523
0       2            456        0.617523
0       3            789        0.4
0       4            987        1.1
1       5            654        3.2

任何想法如何实现? 我在考虑使用这个

df['score'] = df['score'].fillna(something)

2 个答案:

答案 0 :(得分:2)

我认为您可以使用combine_firstfillna,但首先set_index用于对齐数据:

df1 = df1.set_index('p_id_y')
df1['score'] = df1['score'].combine_first(df2.set_index('p_id')['score'])
#df1['score'] = df1['score'].fillna(df2.set_index('p_id')['score'])

print (df1.reset_index())
   p_id_y  main_id     score
0     123        1  0.617523
1     456        2  0.617523
2     789        3  0.400000
3     987        4  1.100000
4     654        5  3.200000

答案 1 :(得分:2)

使用fillnajoin

df.fillna(df[['p_id_y']].join(df2.set_index('p_id'), on='p_id_y'))

enter image description here

相关问题