【问题标题】:TypeError: field col1: LongType can not accept object '' in type <class 'str'>TypeError:字段 col1:LongType 不能接受类型 <class 'str'> 中的对象''
【发布时间】:2021-12-05 16:41:51
【问题描述】:

我在 python 中有这样的 json:

example = [{"col1":"","col2":"","col3":52272}, ...]

json 的列可能为空。空值为 ""。

我创建了 spark 架构:

schema = StructType([
   StructField("col1", LongType(), True),
   StructField("col2", LongType(), True),
   StructField("col3", LongType(), True),]

我尝试像这样获取 spark 数据帧:

pandas_df = pd.DataFrame(example)
spark_df = spark.createDataFrame(pandas_df, schema = schema)

但我得到了那个错误:

TypeError: field col1: LongType can not accept object '' in type <class 'str'>

什么解决了这个错误? 如果我使用此列的其他类型,也会发生同样的错误。

【问题讨论】:

  • 您为 long 类型编写了一个模式,但使用的数据是空字符串 ""。这需要转换为整数。您想使用什么值?或者您想完全排除这些数据?

标签: python json pandas pyspark


【解决方案1】:

正如@tdelaney 评论的那样,您的架构并未反映您的数据。

你可以试试这样的:

from pyspark.sql import SparkSession
import pyspark.sql.functions as F
from pyspark.sql.types import IntegerType, StringType, StructField, StructType

if __name__ == "__main__":
    spark = SparkSession.builder.master("local").appName("Test").getOrCreate()
    data = [{"col1": "", "col2": "", "col3": 52272}]
    schema = StructType(
        [
            StructField("col1", StringType(), True),
            StructField("col2", StringType(), True),
            StructField("col3", IntegerType(), True),
        ]
    )
    df = spark.createDataFrame(data=data, schema=schema)

这给出了:

+----+----+-----+
|col1|col2|col3 |
+----+----+-----+
|    |    |52272|
+----+----+-----+

例如,如果您想用None 替换空字符串,您可以使用:

df = df.withColumn("col2", F.when(F.col("col2") != "", F.col("col2")).otherwise(None))

这给出了:

+----+----+-----+
|col1|col2|col3 |
+----+----+-----+
|    |null|52272|
+----+----+-----+

【讨论】:

    猜你喜欢
    • 2019-11-30
    • 2020-10-30
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多