Reputation: 103
I need some help handling the above error. So far my searches didn't return any solution. Code is below. Works for some datasets but raises an error for others.
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'
I am using Spyder 3.3.4 Python 3.7.3 64-bit | Qt 5.9.6 | PyQt5 5.9.2 | Windows 10
Thank you for your help.
Upvotes: 1
Views: 9706
Reputation: 779
This worked for me
a = np.array(df_cols)
aver = np.nanmean(a,dtype='float32')
Upvotes: 1
Reputation: 103
I solved this using Pandas mean() after converting my df_cols to series. Pandas mean considers all entries as object and takes care of NaN.
Upvotes: 2
Reputation: 231605
df_cols
in the problem cases is probably object
dtype. pandas
freely uses this dtype, as for strings or None
contents.
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'
Upvotes: 0