gpt4 book ai didi

python - 将 "nan"值转换为 numpy 矩阵中不同于 0 的不同值

转载 作者:太空宇宙 更新时间:2023-11-04 10:16:27 30 4
gpt4 key购买 nike

我有这样一个 numpy 矩阵:

[[182 93 107 ..., nan nan -1]
[182 93 107 ..., nan nan -1]
[182 93 110 ..., nan nan -1]
...,
[188 95 112 ..., nan nan -1]
[188 97 115 ..., nan nan -1]
[188 95 112 ..., nan nan -1]]

我想将 nan 值更改为非零值。为此,我使用了这种技术:

x_train[np.isnan(x_train)] = -10

但是我得到了这个错误:

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''.

我该如何解决这个问题?

谢谢,

最佳答案

如果您的初始数组是可以有意义地解释为 float 的字符串,那么您可以使用 astype 进行转换:

b = np.array([['182', '93', '107', 'nan', 'nan', '-1'],
['182', '93', '107', 'nan', 'nan', '-1'],
['182', '93', '110', 'nan', 'nan', '-1'],
['188', '95', '112', 'nan', 'nan', '-1'],
['188', '97', '115', 'nan', 'nan', '-1'],
['188', '95', '112', 'nan', 'nan', '-1']])

c = b.astype(np.float)
c[np.isnan(c)]=-10

array([[ 182., 93., 107., -10., -10., -1.],
[ 182., 93., 107., -10., -10., -1.],
[ 182., 93., 110., -10., -10., -1.],
[ 188., 95., 112., -10., -10., -1.],
[ 188., 97., 115., -10., -10., -1.],
[ 188., 95., 112., -10., -10., -1.]])

关于python - 将 "nan"值转换为 numpy 矩阵中不同于 0 的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35150593/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com