我有一个(M x N)
numpy数组,其中包含字符串值,数值和nans。我想删除包含NaN
值的行。我已经试过:从具有字符串值和数值的numpy数组中删除NaN
arr[~np.isnan(arr)]
但我得到的错误:
我有一个(M x N)
numpy数组,其中包含字符串值,数值和nans。我想删除包含NaN
值的行。我已经试过:从具有字符串值和数值的numpy数组中删除NaN
arr[~np.isnan(arr)]
但我得到的错误:
我明白你的错误,如果我做一个对象数组D型:我用
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 ''save''
解决方案
In [112]: arr=np.ones((3,2),object)
In [113]: arr
Out[113]:
array([[1, 1],
[1, 1],
[1, 1]], dtype=object)
In [114]: np.isnan(arr)
...
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''
那dtype
是唯一一个可以混合数字,字符串和np.nan
(这是一个浮点数)。你不能用这个做很多全阵列操作。
我不能轻易测试您的解决方案,因为几个变量是未知的。
对于更一般的arr
,我没有看到如何在不迭代行和列的情况下移除行,测试每个值是否为数字,以及数字是否为isnan
。 np.isnan
是挑剔的,只能操作浮动。
正如'可能重复'中所提到的,熊猫isnull
更为一般。
所以基本上两点:
什么是良好的测试方法,可以处理字符串以及数字
让您可以进行完整的迭代,假设数组是D型对象。
np.isnan on arrays of dtype "object" 我在这里的解决方案是在一维数组做一个列表理解循环。
,从我可以测试的arr
每个元素:
In [125]: arr
Out[125]:
array([['str', 1],
[nan, 'str'],
[1, 1]], dtype=object)
In [136]: for row in arr:
...: for col in row:
...: print(np.can_cast(col,float) and np.isnan(col))
False
False
True
False
False
False
看看我发布的评论。解决办法是使用'pandas.isnull' –
如果你安装了'pandas'。 – hpaulj
一种解决方法是你可以使用np.sum()来总结每行了。因为nan + float = nan,所以你可以得到哪些行包含nan值。
np.sum(arr,axis = 1)
rowsWithoutNaN = [ not(np.isnan(i)) for i in b]
result = np.array([val for shouldKeep, val in zip(rowsWithoutNaN,arr) if shouldKeep])
如果'arr.dtype'是浮动的,这将工作。但OP声称它也包含字符串。 – hpaulj
的[高效检查是否任意物体为NaN在Python/numpy的/大熊猫?](可能的复制http://stackoverflow.com/questions/18689512/efficiently-checking-if-arbitrary-object-is- nan-in-python-numpy-pandas) –
它是2D,但是dtype是什么?对象,字符串? – hpaulj