Python CSV列表转Spark DataFrame遇格式异常,求解决
解决Python CSV字符串列表转Spark DataFrame的问题
你的代码存在两个关键问题:
sc.parallelize([result])把整个result列表作为单个元素传入RDD,导致Spark只识别到一行数据- 用
spark.read.csv读取时,错误解析了列表的括号和引号,导致数据混入多余符号
以下是两种可行的解决方案:
方法一:直接处理CSV字符串RDD
直接并行化原result列表(不要额外套一层[]),让每个CSV字符串成为RDD的独立行,再用指定Schema读取:
from pyspark.sql.types import StructType, StructField, StringType result =['2016,F,555123,031a1f7d-1885-4719-95e6-d4b851633fe1', '2016,F,555123,23300425-c475-465a-8bf1-e306fa5bd9d1'] testSchema = StructType([ StructField('col1', StringType(), True), StructField('col2', StringType(), True), StructField('col3', StringType(), True), StructField('id', StringType(), True) ]) # 直接并行化原列表,每个元素对应一行CSV数据 rdd = sc.parallelize(result) frame = spark.read.schema(testSchema).csv(rdd) display(frame)
方法二:拆分字符串后创建Row对象
如果需要更灵活的字段处理,可以手动拆分每个CSV字符串,生成Row对象后转换为DataFrame:
from pyspark.sql import Row from pyspark.sql.types import StructType, StructField, StringType result =['2016,F,555123,031a1f7d-1885-4719-95e6-d4b851633fe1', '2016,F,555123,23300425-c475-465a-8bf1-e306fa5bd9d1'] testSchema = StructType([ StructField('col1', StringType(), True), StructField('col2', StringType(), True), StructField('col3', StringType(), True), StructField('id', StringType(), True) ]) # 拆分每个CSV字符串,生成Row实例列表 row_list = [Row(*item.split(',')) for item in result] frame = spark.createDataFrame(row_list, schema=testSchema) display(frame)
验证单列查询
两种方法生成的DataFrame都支持正常的单列查询,例如:
# 查询col1列的所有数据 frame.select('col1').show()
内容的提问来源于stack exchange,提问作者amamagar
相关产品推荐
相关产品推荐

