【发布时间】:2021-10-05 02:17:08
【问题描述】:
我有一个 pandas.DataFrame 对象,其中包含大约 100 列和 200000 行数据。我正在尝试将其转换为布尔数据框,其中 True 表示该值大于阈值,False 表示它小于阈值,并且保持 NaN 值。
如果没有 NaN 值,我运行大约需要 60 毫秒:
df >= threshold
但是当我尝试处理 NaN 时,以下方法有效,但速度很慢(20 秒)。
def func(x):
if x >= threshold:
return True
elif x < threshold:
return False
else:
return x
df.apply(lambda x: x.apply(lambda x: func(x)))
有没有更快的方法?
【问题讨论】:
-
尝试将您的
func替换为以下行:return x >= threshold if x is not None else x,它可能会更快。顺便说一句,你为什么分配两个lambda x?df.apply(func)会成功的。 -
@DeepSpace 花了同样的时间