PySpark:StructField(…,…,False)总是返回“nullable=true”,而不是“nullable=False”`

2024-05-17 02:37:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚来PySpark,正面临一个奇怪的问题。我试图在加载CSV数据集时将某列设置为不可为空。我可以用一个非常小的数据集来复制我的案例(test.csv):

col1,col2,col3
11,12,13
21,22,23
31,32,33
41,42,43
51,,53

第5行第2列有一个空值,我不想在DF中得到该行。我将所有字段设置为不可为空(nullable=false),但我得到一个模式,其中所有三列都有nullable=true。即使我将这三列都设置为不可为空,也会发生这种情况!我正在运行最新版本的Spark,2.0.1。

代码如下:

from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *

spark = SparkSession \
    .builder \
    .appName("Python Spark SQL basic example") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()

struct = StructType([   StructField("col1", StringType(), False), \
                        StructField("col2", StringType(), False), \
                        StructField("col3", StringType(), False) \
                    ])

df = spark.read.load("test.csv", schema=struct, format="csv", header="true")

df.printSchema()返回:

root
 |-- col1: string (nullable = true)
 |-- col2: string (nullable = true)
 |-- col3: string (nullable = true)

以及df.show()返回:

+----+----+----+
|col1|col2|col3|
+----+----+----+
|  11|  12|  13|
|  21|  22|  23|
|  31|  32|  33|
|  41|  42|  43|
|  51|null|  53|
+----+----+----+

虽然我希望这样:

root
 |-- col1: string (nullable = false)
 |-- col2: string (nullable = false)
 |-- col3: string (nullable = false)

+----+----+----+
|col1|col2|col3|
+----+----+----+
|  11|  12|  13|
|  21|  22|  23|
|  31|  32|  33|
|  41|  42|  43|
+----+----+----+

Tags: csvfromimportfalsetruesqlstringspark