python处理nan方式

python处理nan方式

import numpy as np
#t = np.arange(24,dtype = float).reshape(4,6)
t = np.arange(24).reshape(4,6).astype(float)
print(t)
#np.nan:赋值 nan
t[1,3:] = np.nan
#t[np.isnan(t)]=0给t中nan的位置赋值0
print(t)

#print(type(t[1,1]))
#np.isnan(t):结果为一个false和true组成的矩阵,是nan则对应矩阵的位置为true,否则为false
print(np.isnan(t))

print(t.shape)
for i in range(t.shape[1]):
#遍历列
temp_col = t[:,i]
# np.count_nonzero()判断非零 个数,即true的个数
nan_num = np.count_nonzero(temp_col !=temp_col)
print(temp_col !=temp_col)
print(np.count_nonzero(temp_col !=temp_col))
#存在nan时
if nan_num !=0:
#temp_col[temp_col == temp_col]把判断temp_col == temp_col对应 true的位置的值取出来
temp_col_not_nan = temp_col[temp_col == temp_col]
print(temp_col == temp_col)
print(temp_col[temp_col == temp_col])
#np.mean()计算平均值
temp_col[np.isnan(temp_col)] = np.mean(temp_col_not_nan)

输出结果:
[[ 0. 1. 2. 3. 4. 5.]
[ 6. 7. 8. 9. 10. 11.]
[12. 13. 14. 15. 16. 17.]
[18. 19. 20. 21. 22. 23.]]
[[ 0. 1. 2. 3. 4. 5.]
[ 6. 7. 8. nan nan nan]
[12. 13. 14. 15. 16. 17.]
[18. 19. 20. 21. 22. 23.]]
[[False False False False False False]
[False False False True True True]
[False False False False False False]
[False False False False False False]]
(4, 6)
[False False False False]
0
[False False False False]
0
[False False False False]
0
[False True False False]
1
[ True False True True]
[ 3. 15. 21.]
[False True False False]
1
[ True False True True]
[ 4. 16. 22.]
[False True False False]
1
[ True False True True]
[ 5. 17. 23.]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值