当所有值都是NaN和字符串时,nanpercentile出错

时间:2016-10-23 20:14:45

标签: numpy

当参数是NaN和字符串

时,我遇到了nanpercentile的问题

这个运行正常:

In [133]: np.nanpercentile([np.nan, np.nan], 25.0)
Out[133]: nan

但这是我的问题:

In [136]: np.nanpercentile([np.nan, np.nan, 'tc'], 25.0)
...
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''

我调查了官方doc,但我找不到如何跳过非数字值或替代方法。我想我在这里缺少的是模仿Pandas的例子:

DataFrame.min(numeric_only=True)

相关版本:

In [132]: pd.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 2.7.12.final.0
python-bits: 64
OS: Linux
OS-release: 4.4.0-45-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8

pandas: 0.18.1
nose: 1.3.7
pip: 8.1.2
setuptools: 27.2.0
Cython: 0.24.1
numpy: 1.11.1
scipy: 0.18.1
statsmodels: 0.6.1
xarray: None
IPython: 5.1.0
sphinx: 1.4.6
patsy: 0.4.1
dateutil: 2.5.3
pytz: 2016.6.1
blosc: None
bottleneck: 1.1.0
tables: 3.2.3.1
numexpr: 2.6.1
matplotlib: 1.5.3
openpyxl: 2.3.2
xlrd: 1.0.0
xlwt: 1.1.2
xlsxwriter: 0.9.3
lxml: 3.6.4
bs4: 4.5.1
html5lib: None
httplib2: None
apiclient: None
sqlalchemy: 1.0.13
pymysql: None
psycopg2: None
jinja2: 2.8
boto: 2.42.0
pandas_datareader: None

1 个答案:

答案 0 :(得分:2)

这个函数的第一件事就是确保输入是一个数组。请注意当我在列表中尝试多个变体时会发生什么

In [1164]: np.array([1,2,3])
Out[1164]: array([1, 2, 3])       # integer array
In [1165]: np.array([1,2,3,np.nan])
Out[1165]: array([  1.,   2.,   3.,  nan])   # float array
In [1166]: np.array([1,2,3,np.nan,'str'])
Out[1166]: 
array(['1', '2', '3', 'nan', 'str'], 
      dtype='<U32')

使用字符串值,结果是字符串数组。

然后检查nan值:

In [1168]: np.isnan(np.array([1,2,3,np.nan]))
Out[1168]: array([False, False, False,  True], dtype=bool)
In [1169]: np.isnan(np.array([1,2,3,np.nan,'str']))
...
TypeError: ufunc 'isnan' not supported for the input types,...

最好从列表中清除字符串值,例如:

In [1174]: [i for i in [1,2,3,np.nan,'str'] if not isinstance(i,str)]
Out[1174]: [1, 2, 3, nan]
In [1176]: nlist=[i for i in [1,2,3,np.nan,'str'] if not isinstance(i,str)]
In [1177]: np.array(nlist)
Out[1177]: array([  1.,   2.,   3.,  nan])
In [1178]: np.isnan(np.array(nlist))
Out[1178]: array([False, False, False,  True], dtype=bool)
In [1180]: np.nanpercentile(nlist,.2)
Out[1180]: 1.004

至于列表全部为nan时的运行时错误,请注意它和percentile不喜欢使用空列表。

In [1187]: np.nanpercentile([],.2)
/usr/lib/python3/dist-packages/numpy/lib/nanfunctions.py:675: RuntimeWarning: Mean of empty slice
  warnings.warn("Mean of empty slice", RuntimeWarning)
Out[1187]: nan