我正在通过Spark加载数据集,并且需要确保导入的数据在数据帧中的任何位置都不包含某些值(目前为Null、NaN和空字符串,但以后可能会有其他值)。我只需要知道“在数据帧中的任何地方是否至少存在一个值x、y或z?”。获得此布尔响应的计算最佳方法是什么?
我更喜欢像下面这样的东西,并且是一些快速成功的东西(在找到第一个实例时返回True;只有在它返回False的情况下才读取整个数据帧)。
bad_value: bool = df.exists([None, float("NaN"), "", "foo"])这是一种天真的方法,然而,这执行了一个昂贵的计数操作并使用了一个循环:
from typing import Any
from pyspark.sql import DataFrame
from pyspark.sql.functions import isnan
def val_in_df(df: DataFrame, val: Any) -> bool:
for c in df.columns:
count = df.filter((df[c] == val)).count()
if count > 0:
return True
return False
df = spark.read.csv("untrusted/data/file.csv", header=True)
if val_in_df(df, None):
print("There is a null in the df")
if val_in_df(df, float("NaN")):
print("There is a NaN in the df")
if val_in_df(df, "")):
print("There is an empty string in the df")
if val_in_df(df, "foo"):
print("The string 'foo' is a value somewhere in the df")发布于 2021-01-22 07:38:28
您可以使用functools.reduce链接过滤条件。下面是一个检查所有列的空值的示例:
import functools
from pyspark.sql.functions import col
null_cols = [col(c).isNull() for c in df.columns]
filter_null_condition = functools.reduce(
lambda acc, x: acc | x, null_cols[1:], null_cols[0]
)
nulls_count = df.filter(filter_null_condition).count()
if nulls_count:
print("There is a null in the df")https://stackoverflow.com/questions/65837164
复制相似问题