小编ctl*_*ctl的帖子

使用空元素在 pyspark 数据帧 read.csv 中设置架构

我有一个数据集(示例),当导入时

df = spark.read.csv(filename, header=True, inferSchema=True)
df.show()
Run Code Online (Sandbox Code Playgroud)

会将带有“NA”的列分配为 stringType(),我希望它是 IntegerType()(或 ByteType())。

推断模式

然后我尝试设置

schema = StructType([
    StructField("col_01", IntegerType()),
    StructField("col_02", DateType()),
    StructField("col_03", IntegerType())
])
df = spark.read.csv(filename, header=True, schema=schema)
df.show()
Run Code Online (Sandbox Code Playgroud)

输出显示'col_03' = null的整行为空。

full_row_null

但是col_01col_02返回适当的数据,如果它们被调用

df.select(['col_01','col_02']).show()
Run Code Online (Sandbox Code Playgroud)

row_actually_not_null

我可以通过后期转换col_3的数据类型来找到解决此问题的方法

df = spark.read.csv(filename, header=True, inferSchema=True)
df = df.withColumn('col_3',df['col_3'].cast(IntegerType()))
df.show()
Run Code Online (Sandbox Code Playgroud)

import_then_cast

,但我认为这并不理想,如果我可以通过设置模式直接为每列分配数据类型会更好。

有人能指导我做错什么吗?或者在导入后转换数据类型是唯一的解决方案?也欢迎对这两种方法的性能提出任何意见(如果我们可以使分配模式起作用)。

谢谢,

python-3.x pyspark spark-dataframe pyspark-sql

6
推荐指数
1
解决办法
2万
查看次数