【问题标题】:"NULL" instead of null values in PySpark\"NULL\" 而不是 PySpark 中的空值
【发布时间】:2022-11-06 04:29:57
【问题描述】:

我有一个数据框 df,但是因为它的 3 个通常应该是“double”的列具有像“NULL”这样的值,所以自动类型被转换为字符串。

df =

col_0      col_1      col_2            col_3
Word       73452     3859.0     4734.0000000
Word1      23452     3859.0             NULL
Word2      73452       NULL     4758.0000000
Word1      73454       NULL     4756.0000000
Word2      73452     3456.0     4758.0000000

我想改变这一点,我的尝试是:

from pyspark.sql.types import DoubleType

def my_function(df):
    df_1 = df.withColumn("col_1", df["col_1"].cast(DoubleType()))
    df_2 = df_1.withColumn("col_2", df_1["col_2"].cast(DoubleType()))
    df_3 = df_2.withColumn("col_3", df_2["col_3"].cast(DoubleType()))
    return df_3

但我不知道如何用空的 null 替换字符串“NULL”。即便如此,这样就够了吗?

【问题讨论】:

  • 上面的NULL 是什么?是文字吗?
  • 我对其进行了测试 - .cast(DoubleType()) 将每个非双重可转换条目替换为您期望的空类型。

标签: python string dataframe pyspark double


【解决方案1】:

您可以尝试使用 Python 的 None 类型替换值为 NULL 的字符串,然后转换为正确的类型,如下所示:

df = spark.createDataFrame([("Word1", 23452, 3859.0, "NULL"), ("Word2", 73452, "NULL", 4758.0000000)], "col_0: string, col_1: int, col_2: string, col_3: string")
print(df.dtypes)

# [('col_0', 'string'), ('col_1', 'int'), ('col_2', 'string'), ('col_3', 'string')]

from pyspark.sql.functions import col

print(df.na.replace("NULL", None).select(col("col_0"), col("col_1").cast("int"), col("col_2").cast("double"), col("col_3").cast("double")).dtypes)

# [('col_0', 'string'), ('col_1', 'int'), ('col_2', 'double'), ('col_3', 'double')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多