首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何判断Spark dataframe中是否存在某个值?

问如何判断Spark dataframe中是否存在某个值?
EN

Stack Overflow用户
提问于 2021-01-22 07:15:52
回答 1查看 855关注 0票数 1

我正在通过Spark加载数据集,并且需要确保导入的数据在数据帧中的任何位置都不包含某些值(目前为Null、NaN和空字符串,但以后可能会有其他值)。我只需要知道“在数据帧中的任何地方是否至少存在一个值x、y或z?”。获得此布尔响应的计算最佳方法是什么?

我更喜欢像下面这样的东西,并且是一些快速成功的东西(在找到第一个实例时返回True;只有在它返回False的情况下才读取整个数据帧)。

代码语言:javascript
复制
bad_value: bool = df.exists([None, float("NaN"), "", "foo"])

这是一种天真的方法,然而,这执行了一个昂贵的计数操作并使用了一个循环:

代码语言:javascript
复制
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")
EN

回答 1

Stack Overflow用户

发布于 2021-01-22 07:38:28

您可以使用functools.reduce链接过滤条件。下面是一个检查所有列的空值的示例:

代码语言:javascript
复制
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")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65837164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档