如何检查LazyFrame是否为空?

问题描述 投票:0回答:1

Polars 数据框有一个

is_empty
属性:

import polars as pl

df = pl.DataFrame()
df.is_empty()  # True

df = pl.DataFrame({"a": [], "b": [], "c": []})
df.is_empty()  # True

Polarlazyframes 的情况并非如此,因此我设计了以下辅助函数:

def is_empty(data: pl.LazyFrame) -> bool:
    return (
        data.width == 0  # No columns
        or data.null_count().collect().sum_horizontal()[0] == 0  # Columns exist, but are empty
    )


other = pl.LazyFrame()
other.pipe(is_empty)  # True

other = pl.LazyFrame({"a": [], "b": [], "c": []})
other.pipe(is_empty)  # True

有更好的方法吗?我所说的更好是指要么不收集,要么在无法避免收集的情况下减少内存占用。

python memory python-polars lazyframe
1个回答
0
投票

TLDR。 使用

lf.collect().is_empty()

一般来说,要检查Lazyframe是否为空,需要将相应的frame具体化为DataFrame。在没有实际执行底层计算的情况下,极坐标无法推断帧是否为空(例如,如果复杂的过滤器删除了所有行)。

如果 LazyFrame 没有任何列,则调用

.collect()
也很简单,因为不需要实际计算任何操作。

因此,只需使用

lf.collect().is_empty()

似乎是最好的方法。

© www.soinside.com 2019 - 2024. All rights reserved.