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

Jupyter Notebook加载CSV后字符串显示异常问题求助

Jupyter中Pandas DataFrame文本显示为无法选中的加粗/斜体问题

问题重现

你在Jupyter Notebook加载CSV到Pandas DataFrame后,发现某列部分条目显示为无法选中的加粗/斜体格式,执行代码如下:

import pandas as pd

pd.options.display.max_rows = None
pd.options.display.max_columns = None
pd.options.display.float_format = '{:,.2f}'.format
pd.options.display.max_colwidth = None

df = pd.read_csv('../data.csv')
df.head()

该异常条目的原始文本为:

"BRIEF: For the nine months ended 30 September 2024, Alcoa Corp revenues increased 6% to $8.41B. Net loss decreased 72% to $142M. Revenues reflect Alumina segment increase of 13% to $3.07B, Aluminum segment increase of 2% to $5.34B. Lower net loss reflects Equity loss (gain) decrease of 87% to $24M (expense), Gain/Loss on Derivatives - Hedging increase from $3M (expense) to $39M (income). Dividend per share remained flat at $0.30."

原因分析

核心原因是Jupyter Notebook的自动LaTeX公式渲染机制:文本中的$符号会被Jupyter识别为LaTeX公式的起始/结束标记,将$包裹的内容(比如$8.41B里的8.41B)渲染为斜体公式格式,这类渲染后的元素属于页面生成的特殊节点,无法直接选中复制,看起来像是异常格式。

Pandas在Jupyter中默认用HTML方式渲染DataFrame,不会主动转义$这类特殊符号,因此触发了Jupyter的Markdown/LaTeX渲染逻辑。

解决方法

  • 方法1:强制Pandas以纯文本格式显示
    替换df.head()为纯文本输出,绕过HTML渲染:

    print(df.to_string())
    

    或者设置全局显示选项,关闭HTML渲染:

    pd.set_option('display.notebook_repr_html', False)
    df.head()
    
  • 方法2:转义文本中的$符号
    加载CSV后,对目标列的$进行转义,避免被Jupyter解析:

    # 替换为你的目标列名
    df['目标列名'] = df['目标列名'].str.replace('$', r'\$', regex=False)
    df.head()
    

    转义后的\$会被识别为普通字符,不再触发公式渲染。

  • 方法3:禁用Jupyter的自动LaTeX渲染
    在Notebook开头执行以下代码,关闭当前Notebook的LaTeX自动解析:

    %%javascript
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: []
        }
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 04:50:05