numpy nanmean()'float'对象没有属性'dtype'错误

时间:2019-04-29 15:23:46

标签: python numpy mean

我需要一些帮助来处理上述错误。到目前为止,我的搜索没有返回任何解决方案。代码如下。适用于某些数据集,但对其他数据集则会产生错误。

a = np.array(df_cols)
aver = np.nanmean(a)
    File "…\Continuum\anaconda3\lib\site-packages\numpy\lib\nanfunctions.py", line 916, in nanmean

    avg = _divide_by_count(tot, cnt, out=out)

    File "…\Continuum\anaconda3\lib\site-packages\numpy\lib\nanfunctions.py", line 190, in _divide_by_count

    return a.dtype.type(a / b)

    AttributeError: 'float' object has no attribute 'dtype'

我正在使用Spyder 3.3.4 Python 3.7.3 64位| Qt 5.9.6 | PyQt5 5.9.2 | Windows 10

谢谢您的帮助。

3 个答案:

答案 0 :(得分:0)

在有问题的情况下,

df_cols可能是object dtype。 pandas自由使用此dtype,例如用于字符串或None的内容。

In [117]: np.nanmean(np.array([1.2,np.nan]))      # a float array                                         
Out[117]: 1.2

In [118]: np.nanmean(np.array([1.2,np.nan], object))   # object dtype array                    
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-118-ca706fd2a20e> in <module>
----> 1 np.nanmean(np.array([1.2,np.nan], object))

/usr/local/lib/python3.6/dist-packages/numpy/lib/nanfunctions.py in nanmean(a, axis, dtype, out, keepdims)
    914     cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=keepdims)
    915     tot = np.sum(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
--> 916     avg = _divide_by_count(tot, cnt, out=out)
    917 
    918     isbad = (cnt == 0)

/usr/local/lib/python3.6/dist-packages/numpy/lib/nanfunctions.py in _divide_by_count(a, b, out)
    188         else:
    189             if out is None:
--> 190                 return a.dtype.type(a / b)
    191             else:
    192                 # This is questionable, but currently a numpy scalar can

AttributeError: 'float' object has no attribute 'dtype'

答案 1 :(得分:0)

在将df_cols转换为series之后,我使用了Pandas mean()解决了这个问题。熊猫意味着将所有条目视为对象并处理NaN。

答案 2 :(得分:0)

这对我有用

 a = np.array(df_cols)
 aver = np.nanmean(a,dtype='float32')