我在S3上有两个csv
文件:
# a1.csv
a,b
3,4
字符串
和
# b2.csv
a,c
1,"text"
型
我想一次读取这两个文件,确保最终的嵌套框架包含所有文件中的所有列,如下所示:
+---+----+----+
| a| b| c|
+---+----+----+
| 1|null|text|
| 3| 4|null|
+---+----+----+
型
我尝试了inferSchema
和schema
选项,但它们没有提供我期望的结果。
选项1:
df = spark.read\
.option("header", True)\
.option("inferSchema", True)\
.csv("s3a://test/*.csv")\
.show()
+---+----+
| a| c|
+---+----+
| 1|text|
| 3| 4|
+---+----+
型
备选方案2:
from pyspark.sql.types import StructType, StructField, IntegerType, StringType
schema = StructType([
StructField("a", IntegerType(), False)
,StructField("b", IntegerType(), True)
,StructField("c", StringType(), True)
])
df = spark.read\
.option("header", True)\
.schema(schema)\
.csv("s3a://test/*.csv")\
.show()
+---+----+----+
| a| b| c|
+---+----+----+
| 1|null|null|
| 3| 4|null|
+---+----+----+
型
有什么办法吗?
1条答案
按热度按时间wpcxdonn1#
如果文件格式是parquet,那么我们可以通过指向包含多个文件的文件夹使用mergeSchema选项轻松合并模式,但对于CSV文件,我们没有该选项。
您可以使用unionByName函数来获得所需的结果。
遍历文件夹,将文件读入到嵌套框架中,然后调用unionByName函数。
字符串