在pandas中匹配列匹配的另一个数据帧中替换NaN值的正确方法

kas*_*yap 1 python numpy pandas

我是pandas的新手,并试图用df2替换列值(NaN),列值匹配.并面临以下错误.

df1
unique_col  |  Measure
944537          NaN
7811403         NaN 
8901242114307     1 

df2
unique_col  |  Measure
944537           18
7811403          12 
8901242114307    17.5



df1.loc[(df1.unique_col.isin(df2.unique_col) &
                       df1.Measure.isnull()), ['Measure']] = df2[['Measure']]
Run Code Online (Sandbox Code Playgroud)

我有两个数据帧,有300万条记录,并且在执行以下操作时遇到以下错误:

ValueError:无法从重复轴重新索引

raf*_*elc 7

你轻松填充nans的方法是使用fillna功能.在你的情况下,如果你有dfs(注意索引)

    unique_col      Measure
0   944537          NaN
1   7811403         NaN
2   8901242114307   1.0


    unique_col      Measure
0   944537          18.0
1   7811403         12.0
2   8901242114307   17.5
Run Code Online (Sandbox Code Playgroud)

你可以简单

>>> df.fillna(df2)


    unique_col       Measure
0   944537           18.0
1   7811403          12.0
2   8901242114307    1.0
Run Code Online (Sandbox Code Playgroud)

如果索引一样的上面,你可以将它们设置为相同,并使用同一功能

df = df.set_index('unique_col')
df.fillna(df2.set_index('unique_col'))
Run Code Online (Sandbox Code Playgroud)