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

Set schema in pyspark dataframe read.csv with null elements

我有一个数据集(示例),当使用

导入时
df = spark.read.csv(filename, header=True, inferSchema=True)
df.show()

将 '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()

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

但是 col_01col_02 return 如果用

df.select(['col_01','col_02']).show()

我可以通过 post 转换 col_3

的数据类型来找到解决这个问题的方法
df = spark.read.csv(filename, header=True, inferSchema=True)
df = df.withColumn('col_3',df['col_3'].cast(IntegerType()))
df.show()

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

谁能指导我做错了什么?或者导入后转换数据类型是唯一的解决方案?也欢迎任何关于这两种方法的性能的评论(如果我们可以使分配模式起作用)。

谢谢,

尝试一次 - (但这会将每一列读取为字符串类型。您可以根据需要输入种姓)

import csv
from pyspark.sql.types import IntegerType

data = []
with open('filename', 'r' ) as doc:
    reader = csv.DictReader(doc)
    for line in reader:
        data.append(line)

df = sc.parallelize(data).toDF()
df = df.withColumn("col_03", df["col_03"].cast(IntegerType()))

您可以使用 nullValue:

在 spark 的 csv 加载器中设置一个新的空值

对于如下所示的 csv 文件:

col_01,col_02,col_03
111,2007-11-18,3
112,2002-12-03,4
113,2007-02-14,5
114,2003-04-16,NA
115,2011-08-24,2
116,2003-05-03,3
117,2001-06-11,4
118,2004-05-06,NA
119,2012-03-25,5
120,2006-10-13,4

并强制架构:

from pyspark.sql.types import StructType, IntegerType, DateType

schema = StructType([
    StructField("col_01", IntegerType()),
    StructField("col_02", DateType()),
    StructField("col_03", IntegerType())
])

您将获得:

df = spark.read.csv(filename, header=True, nullValue='NA', schema=schema)
df.show()
df.printSchema()

    +------+----------+------+
    |col_01|    col_02|col_03|
    +------+----------+------+
    |   111|2007-11-18|     3|
    |   112|2002-12-03|     4|
    |   113|2007-02-14|     5|
    |   114|2003-04-16|  null|
    |   115|2011-08-24|     2|
    |   116|2003-05-03|     3|
    |   117|2001-06-11|     4|
    |   118|2004-05-06|  null|
    |   119|2012-03-25|     5|
    |   120|2006-10-13|     4|
    +------+----------+------+

    root
     |-- col_01: integer (nullable = true)
     |-- col_02: date (nullable = true)
     |-- col_03: integer (nullable = true)