首页 > 解决方案 > 从一个具有浮点数和 NaN 的 1 和 0 创建一个相等的 numpy 数组

问题描述

将与“x1”(同时具有浮点数和 NaN 的数组)大小相等的数组创建为“x2”的最优雅方法是什么,其中:

floating number = 1
NaN = 0

数组是股票价格(1500 天 x 道指 30 股票)。

谢谢!

标签: arraysnumpynan

解决方案


我可以想到三种方式,都使用numpy.isnan

#setup
x = np.array([[1, 2, np.nan], [2.4, 0, 3], [np.nan, np.nan, 9]])
  1. numpy.where
np.where(np.isnan(x), 0, 1)
array([[1, 1, 0],
       [1, 1, 1],
       [0, 0, 1]])
  1. numpy.ndarray.astype
(~np.isnan(x)).astype(int)
array([[1, 1, 0],
       [1, 1, 1],
       [0, 0, 1]])
  1. numpy.divide
np.divide(x, x, out = np.zeros_like(x), where = ~np.isnan(x))
array([[1., 1., 0.],
       [1., 1., 1.],
       [0., 0., 1.]])
#floats instead of integers here

推荐阅读