numpy - 当所有值为 NaN 和字符串时 nanpercentile 出现错误

标签 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

最佳答案

该函数所做的第一件事是确保输入是一个数组。请注意当我在列表上尝试几种变体时会发生什么

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

关于numpy - 当所有值为 NaN 和字符串时 nanpercentile 出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40207367/

相关文章:

python - 检查两个 numpy 数组之间是否相等

python - 如何在 RedHat 上安装 numpy 和 matplotlib?

python - 在 pandas 中计算阿隆指标的有效方法

Python numpy - 随机数的再现性

python - 使用 NumPy 广播的 View

python - NumPy 如何将复数矩阵相乘?

python - 用于有条件减去现有值的 Numpy boolean 索引掩码

python - 复数的表示法不一致

python - 对 3d numpy 数组进行子集化

numpy - 对非常大的一维数组进行排序