用pandas fillna替换NaN

时间:2017-04-26 08:06:26

标签: python pandas

有一个数据框,mat:

    x    y     z    d
0  1.0  1.0  4589  1.0
1  0.0  1.0  4716  1.0
2  0.0  NaN  4984  NaN
3  0.0  NaN  4673  NaN
4  0.0  1.0  4514  1.0
5  NaN  1.0  4614  1.0
6  NaN  1.0  4684  1.0

我试图用一些值填充NaN。所以我试过

mat['x'].fillna(666)
print(mat)

但它返回:

    x    y     z    d
0  1.0  1.0  4589  1.0
1  0.0  1.0  4716  1.0
2  0.0  NaN  4984  NaN
3  0.0  NaN  4673  NaN
4  0.0  1.0  4514  1.0
5  NaN  1.0  4614  1.0
6  NaN  1.0  4684  1.0

我也试过了mat.fillna({'x':666}),但没有任何区别。

,而

gg = mat['x'].fillna(666) 
print(gg)

返回

     x    y     z    d
0  1.0  1.0  4589  1.0
1  0.0  1.0  4716  1.0
2  0.0  NaN  4984  NaN
3  0.0  NaN  4673  NaN
4  0.0  1.0  4514  1.0
5  NaN  1.0  4614  1.0
6  NaN  1.0  4684  1.0
0      1.0
1      0.0
2      0.0
3      0.0
4      0.0
5    666.0
6    666.0

xx = mat.fillna({'x':666})
print(xx)

返回:

0    1.0  1.0  4589  1.0
1    0.0  1.0  4716  1.0
2    0.0  NaN  4984  NaN
3    0.0  NaN  4673  NaN
4    0.0  1.0  4514  1.0
5  666.0  1.0  4614  1.0
6  666.0  1.0  4684  1.0

上面的回报都不是我想要的。我怎么能得到这个:

      x    y     z    d
0    1.0  1.0  4589  1.0
1    0.0  1.0  4716  1.0
2    0.0  NaN  4984  NaN
3    0.0  NaN  4673  NaN
4    0.0  1.0  4514  1.0
5  666.0  1.0  4614  1.0
6  666.0  1.0  4684  1.0

1 个答案:

答案 0 :(得分:1)

使用参数inplace或将bact分配给列输出:

mat['x'].fillna(666, inplace=True) 
print (mat)
       x    y     z    d
0    1.0  1.0  4589  1.0
1    0.0  1.0  4716  1.0
2    0.0  NaN  4984  NaN
3    0.0  NaN  4673  NaN
4    0.0  1.0  4514  1.0
5  666.0  1.0  4614  1.0
6  666.0  1.0  4684  1.0

或者:

mat['x'] = mat['x'].fillna(666) 
print (mat)
       x    y     z    d
0    1.0  1.0  4589  1.0
1    0.0  1.0  4716  1.0
2    0.0  NaN  4984  NaN
3    0.0  NaN  4673  NaN
4    0.0  1.0  4514  1.0
5  666.0  1.0  4614  1.0
6  666.0  1.0  4684  1.0