You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PySpark DataFrame转Pandas切片后转回出现ParseException错误求助

问题解决:PySpark转Pandas切片后转回时的ParseException错误

错误原因

触发ParseException的核心原因有两点:

  1. Schema格式不符合要求:当用字符串指定schema参数时,Spark要求遵循DDL语法,必须同时声明字段名+数据类型(例如Country string),仅写字段名Country会导致解析失败。
  2. Schema与实际数据结构不匹配:df1实际包含Player和Titles两列,但你指定的schema是Country,结构完全不匹配;df2虽对应Country列,但同样缺少数据类型声明。

解决方法

方法1:正确使用DDL格式指定Schema

根据切片后Pandas DataFrame的实际结构,补充字段名和对应数据类型:

import pandas as pd
    
# 构建原始PySpark DataFrame
rows = [['Lee Chong Wei', 69, 'Malaysia'],
        ['Lin Dan', 66, 'China'],
        ['Srikanth Kidambi', 9, 'India'],
        ['Kento Momota', 15, 'Japan']]
columns = ['Player', 'Titles', 'Country']
df = spark.createDataFrame(rows, columns)
  
# 转Pandas并切片
pandas_df = df.toPandas()
df1 = pandas_df.iloc[[2], :2]  # 包含Player、Titles列
df2 = pandas_df.iloc[[2], 2:]  # 包含Country列
  
# 正确指定DDL格式schema转回PySpark
df1 = spark.createDataFrame(df1, schema="Player string, Titles int")
df2 = spark.createDataFrame(df2, schema="Country string")

方法2:让Spark自动推断Schema

Spark可以直接从Pandas DataFrame的结构自动推断schema,无需手动指定:

import pandas as pd
    
# 构建原始PySpark DataFrame
rows = [['Lee Chong Wei', 69, 'Malaysia'],
        ['Lin Dan', 66, 'China'],
        ['Srikanth Kidambi', 9, 'India'],
        ['Kento Momota', 15, 'Japan']]
columns = ['Player', 'Titles', 'Country']
df = spark.createDataFrame(rows, columns)
  
# 转Pandas并切片
pandas_df = df.toPandas()
df1 = pandas_df.iloc[[2], :2]
df2 = pandas_df.iloc[[2], 2:]
  
# 自动推断schema转回PySpark
df1 = spark.createDataFrame(df1)
df2 = spark.createDataFrame(df2)

额外优化:直接用PySpark完成切片(无需转Pandas)

如果数据量较大,转Pandas会占用Driver内存,推荐直接用PySpark API完成切片操作,更高效:

# 直接选取第3行(索引从0开始)的前2列
df1 = df.filter(df.index == 2).select('Player', 'Titles')
# 直接选取第3行的Country列
df2 = df.filter(df.index == 2).select('Country')

内容的提问来源于stack exchange,提问作者Mohammad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 06:50:29