我有一個(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