简体   繁体   English

熊猫:将 df 写入文本文件 - 将 df 向右缩进 5 个空格

[英]pandas: write df to text file - indent df to right by 5 white spaces

I am writing a df to a text file like so:我正在将 df 写入文本文件,如下所示:

file = open("pptx_comparision_log.txt", "w")
df= df.to_string()
file.write(comp_df)

This works fine but how can I indent my df so it sits 5 white spaces to the right.这工作正常,但我如何缩进我的 df 以便它位于右侧 5 个空格。

so from this:所以从这个:

                    dim_pptx  qp_pptx
Absolute Radio        0.0739   0.0753
BBC Asian Network     0.0013   0.0013
BBC Radio 1           0.1441   0.1455
BBC Radio 1Xtra       0.0057   0.0058
BBC Radio 2           0.2336   0.2339

to:到:

                         dim_pptx  qp_pptx
     Absolute Radio        0.0739   0.0753
     BBC Asian Network     0.0013   0.0013
     BBC Radio 1           0.1441   0.1455
     BBC Radio 1Xtra       0.0057   0.0058
     BBC Radio 2           0.2336   0.2339

Is this possible?这可能吗?

Thanks.谢谢。

您可以在转换后通过将df.to_string()替换为" "*5 + df.to_string().replace("\\n", "\\n ")来执行字符串操作。

Riding on @Randy's answer above, wanna suggest a slightly better solution:骑在@Randy 上面的回答上,想提出一个更好的解决方案:

indent = " " * N
df_str = indent + df.to_string().replace("\n", "\n" + indent)

(Choose N as you seem fit) (选N ,看你觉得合适)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM