如何在打印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
相关产品推荐
相关产品推荐

