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

如何在打印pandas DataFrame时实现指定列带单引号的字符串格式化输出

实现方法

你可以通过以下两种方案实现需求:

  • 方案1:使用to_string()自带的formatters参数(推荐)
    该方案不会修改DataFrame存储的原始数据,仅在打印输出时做格式化处理,代码示例如下:
import pandas as pd

x1 = ['A', 'B', 'C', 'D']
x2 = [',', ',', ',', ',']
test_dataframe = pd.DataFrame()
test_dataframe['id'] = x1
test_dataframe['sep'] = x2

print(test_dataframe[['id','sep']].to_string(
    index=False,
    formatters={
        # 给id列的每个值外层包裹单引号
        'id': lambda val: f"'{val}'"
    }
))
  • 方案2:临时修改列值后打印
    如果你可以接受临时修改列数据,或者需要保存格式化后的内容,可以用这个方案:
import pandas as pd

x1 = ['A', 'B', 'C', 'D']
x2 = [',', ',', ',', ',']
test_dataframe = pd.DataFrame()
test_dataframe['id'] = x1
test_dataframe['sep'] = x2

# 给id列所有值包裹单引号
test_dataframe['id'] = test_dataframe['id'].apply(lambda x: f"'{x}'")
print(test_dataframe[['id','sep']].to_string(index=False))

# 如果需要保留原始数据,可先复制副本再修改
# temp_df = test_dataframe.copy()
# temp_df['id'] = temp_df['id'].apply(lambda x: f"'{x}'")
# print(temp_df[['id','sep']].to_string(index=False))

两种方案运行后都会输出你需要的效果:

id sep
'A'   ,
'B'   ,
'C'   ,
'D'   ,

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:54:04