验证 Pyspark 数据框列类型的可靠方法

数据挖掘 数据清理 阿帕奇火花 pyspark 数据框
2022-02-14 18:21:22

如果我从 CSV 读取数据,默认情况下所有列都是“字符串”类型。通常,我使用以下函数检查数据,这些函数概述了数据及其类型

df.dtypes
df.show()
df.printSchema()
df.distinct().count()
df.describe().show()

但是,如果有一个我认为是特定类型的列,例如 Double,如果我没有业务知识,我无法确定所有值是否都是双倍的,因为

  1. 我看不到所有值(数百万个唯一值)
  2. 如果我将其显式转换为 double 类型,spark 会悄悄地转换类型而不抛出任何异常,并且非 double 的值将转换为“null” - 例如

代码:

from pyspark.sql.types import DoubleType

changedTypedf = df_original.withColumn('label', df_control_trip['id'].cast(DoubleType()))

那么确认列类型的最佳方法是什么?

3个回答

如果您没有业务知识,就无法分辨出正确的类型,也无法“确认”它。您最多只能对您的数据集和数据集做出假设,并且您肯定必须检查每个值。

在您的示例中,您创建了label一个将列转换id为双精度的新列。您可以计算所有为 null inlabel但不是 null in 的行id如果此计数为零,您可以假设对于此数据集,您可以将其id用作双精度数。这并不一定意味着在新数据集中对于 column 也是如此id

擎天柱可以帮助你。https://github.com/ironmussa/optimus

初始化 Optimus 后,您可以运行:

op.profiler.run(df, "*", infer=True)

这将为您提供 String、Integer、Float、Bool 和 Date 的计数。有关更多信息,请查看https://github.com/ironmussa/Optimus/blob/master/examples/new-api-profiler.ipynb

我遇到了完全相同的问题,没有输入要转换的列类型。

我的解决方案是获取第一行并将其转换为 dict your_dataframe.first().asDict(),然后使用正则表达式进行迭代以查找特定列的值是否为数字。如果使用空字符串将值设置为 None,则过滤列并获取第一行。

empty_columns = list()
first_row = your_dataframe.first().asDict()
dict_first_row_was_None = dict()   

for (column, value) in first_row.items():
        if value == "":
        empty_columns.append(column)

for column in empty_columns:
    result = your_dataframe.select(column).filter(col(column) != "").first()
        if result is not None:
            dict_first_row_was_None.update(result.asDict())

first_row.update(dict_first_row_was_None)

numeric_parameters = [column for (column, value) in first_row.items() if (re.match(r'YOUR_REGEX', value))]