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

如何在Databricks中整洁显示PySpark DataFrame?

解决Databricks中PySpark DataFrame列标题换行、实现横向滚动显示的问题

问题场景

刚接触Databricks与PySpark,读取文本文件数据集后,使用df.show(truncate=False)展示数据时,出现列标题换行、难以对应内容的问题,希望实现可横向滚动且列标题单行显示的效果。

现有代码

# File location and type
file_location = "/FileStore/tables/2014_GE_By_Precinct.txt"
file_type = "txt"

# The applied options are for txt files. For other file types, these will be ignored.
df = spark.read.option("inferSchema", "true") \
  .option("header", "true") \
  .csv(file_location)

df.show(truncate=False)

解决方案

方法1:使用Databricks内置display()函数(推荐)

Databricks提供了专门的display()函数,替代原生的show(),会生成支持横向滚动的交互式表格,默认保持列标题单行显示,还支持排序、过滤、导出等功能。

修改后的代码:

# 读取数据部分不变
df = spark.read.option("inferSchema", "true") \
  .option("header", "true") \
  .csv(file_location)

# 用display替代show
display(df)

方法2:调整show()的显示参数(仅临时应急)

如果必须使用show(),可以通过设置width参数强制扩大显示宽度,避免列标题换行,但这种方式不够灵活,当列数过多时效果有限:

# 设置足够大的width值,根据实际列数调整
df.show(truncate=False, width=2000)

说明

display()是Databricks环境下最适合的DataFrame可视化方式,不仅解决列换行问题,还能提供更丰富的交互能力,建议优先使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:11:07