【问题标题】:Fastest way to remove the list/tuple contains nan删除列表/元组的最快方法包含 nan
【发布时间】:2017-08-19 16:25:11
【问题描述】:

我遇到Remove a tuple containing nan in list of tuples -- 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。

【问题讨论】:

  • 怎么样:[x for x in merge if not np.nan in x]?
  • 如果不是 x 中的 np.nan 无法检测到 float('nan')
  • nans = {np.nan, float('nan')}; [x for x in merge if not nans.intersection(x)]

标签: python python-2.7 list tuples nan


【解决方案1】:

您可以将nans 放在一个集合中并检查与元组的交集。您可以使用列表理解或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 倍。

【讨论】:

    猜你喜欢
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多