3 回答

TA贡献1852条经验 获得超1个赞
如果您的数组仅包含“合理”(见下文)元素,那么您可以使用以下解决方法:
np.where(X_==X_,X_,0)
合理的意思是元素 e 满足 e==e 唯一的例外是 nan。例如,如果没有用户定义的类用作元素,则应该是这种情况。

TA贡献2065条经验 获得超14个赞
似乎由于对象类型,转换为浮点数不起作用。可能有点hacky,但您可以尝试转换为str:
X_.astype(str).replace('np.NaN', 0).astype(float)

TA贡献2051条经验 获得超10个赞
“对象” dtype 也给我带来了问题。但你astype(np.float64)确实为我工作。谢谢!
print("Creating a numpy array from a mixed type DataFrame can create an 'object' numpy array dtype:")
A = np.array([1., 2., 3., np.nan]); print('A:', A, A.dtype)
B = pd.DataFrame([[1., 2., 3., np.nan,], [1, 2, 3, '4']]
).to_numpy(); print('B:', B, B.dtype, '\n')
print('Converting vanilla A is fine:\n', np.nan_to_num(A, nan=-99), '\n')
print('But not B:\n', np.nan_to_num(B, nan=-99), '\n')
print('Not even this slice of B, \nB[0, :] : ', B[0, :])
print(np.nan_to_num(B[0, :], nan=-99), '\n')
print('The astype(np.float64) does the trick here:\n',
np.nan_to_num(B[0, :].astype(np.float64), nan=-99), '\n\n')
输出:
Creating a numpy array from a mixed type DataFrame can create an 'object' numpy array dtype:
A: [ 1. 2. 3. nan] float64
B: [[1.0 2.0 3.0 nan]
[1.0 2.0 3.0 '4']] object
Converting vanilla A is fine:
[ 1. 2. 3. -99.]
But not B:
[[1.0 2.0 3.0 nan]
[1.0 2.0 3.0 '4']]
Not even this slice of B,
B[0, :] : [1.0 2.0 3.0 nan]
[1.0 2.0 3.0 nan]
The astype(np.float64) does the trick here:
[ 1. 2. 3. -99.]
添加回答
举报