Python:如何用NaNs替换数组中的值?

2024-04-20 07:30:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个矩阵

f=numpy.array([[1,2,3],[2,3,4],[7,8,9]])
>>> f
array([[1, 2, 3],
       [2, 3, 4],
       [7, 8, 9]])

我想用NaNs替换第一行中的值。我该怎么做?我试过了

^{pr2}$

不过,这并不管用

f[0:1]=numpy.zeros(3)

很好用。我能做些什么?在


Tags: numpyzeros矩阵arraynanspr2
2条回答

整型不允许nannumpy中。在

这将起作用:

import numpy as np

f = np.array([[1,2,3],
              [2,3,4],
              [7,8,9]], dtype=float)

f[0, :] = np.nan

# [[ nan  nan  nan]
#  [  2.   3.   4.]
#  [  7.   8.   9.]]

这样做:

import numpy

f = numpy.array([[1,2,3],[2,3,4],[7,8,9]])
f = f.astype(float)
#Put nan in the first row of the matrix f
f[0,] = numpy.nan

结果

^{pr2}$

更多详情

当您键入:

numpy.nan(3)

你可能得到了这个:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object is not callable

这是因为调用numpy.nan时没有任何参数。在

相关问题 更多 >