为什么“numpy.means”是“return'inf”?

2024-10-01 10:21:58 发布

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

我需要计算一个超过1000行的数组的列的平均值。

np.mean(some_array)给我 inf作为输出

但我很确定这些值是可以的。我正在将csv从here加载到我的Data变量中,从我的角度来看,“cement”列是“健康的”。

In[254]:np.mean(Data[:230]['Cement'])
Out[254]:275.75

但如果我增加行数 问题开始了:

In [259]:np.mean(Data[:237]['Cement'])
Out[259]:inf

但是当我看数据的时候

In [261]:Data[230:237]['Cement']
Out[261]:
 array([[ 425. ],
        [ 333.  ],
        [ 250.25],
        [ 491.  ],
        [ 160.  ],
        [ 229.75],
        [ 338.  ]], dtype=float16)

我找不出这种行为的原因 P、 这在使用wakari(基于云的Ipython)的Python 3.x中发生

Numpy版本“1.8.1”

我正在加载数据:

No_Col=9
conv = lambda valstr: float(valstr.replace(',','.'))

c={}
for i in range(0,No_Col,1):
    c[i] = conv

Data=np.genfromtxt(get_data,dtype=float16 , delimiter='\t', skip_header=0, names=True,   converters=c)

Tags: 数据noindatanpcoloutmean
1条回答
网友
1楼 · 发布于 2024-10-01 10:21:58

我想问题是精确性(其他人也有评论)。直接引用文档中的mean()我们看到

Notes

The arithmetic mean is the sum of the elements along the axis divided by the number of elements.

Note that for floating-point input, the mean is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-precision accumulator using the dtype keyword can alleviate this issue.

因为数组是float16类型,所以精度非常有限。使用dtype=np.float64可能会缓解溢出。另请参阅mean()文档中的示例。

相关问题 更多 >