[英]Fastest way to remove the list/tuple contains nan
我有一個與刪除元組列表中包含nan的元組相同的問題-Python說明:
我有兩個形狀為3000的列表,說:
a = list(range(3000))
b = list(range(3000))
某些元素是不同種類的NAN,某些元素是字符串,其中大多數是整數和浮點數,例如:
a[0] = np.nan
b[1] = 'hello'
a[2] = 2.0
b[3] = float('nan')
然后我需要將它們壓縮在一起並刪除包含nan的元組,然后執行以下操作:
merge = zip(a, b)
c = [x for x in merge if not any(isinstance(i, float) and np.isnan(i) for i in x)]
但是性能不是很好,因為我需要做很多檢查,所以花費了很多時間。
當我運行1000次時,大約需要2.2秒。
然后我嘗試這樣做:
c = [x for x in merge if all(i == i for i in x)]
當我運行1000次時,大約需要1.1秒。
我想知道是否有任何更快的方法來刪除包含NaN的元組? 請注意,元組中存在多種NaN。
您可以將nan
放入集合中,並檢查與元組的交集。 您可以使用列表itertools.filterfalse
或itertools.filterfalse
:
In [17]: a = range(3000)
In [18]: merge = list(zip(a, a))
In [19]: %timeit [x for x in merge if not nans.intersection(x)]
1000 loops, best of 3: 566 us per loop
In [20]: %timeit [x for x in merge if all(i == i for i in x)]
1000 loops, best of 3: 1.13 ms per loop
In [21]: %timeit list(filterfalse(nans.intersection, merge))
1000 loops, best of 3: 402 us per loop
使用filterfalse
的最后一種方法大約快3倍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.