【问题标题】:Printing Pandas dataframe to a text file and adding lines, why is \n adding a space?将 Pandas 数据框打印到文本文件并添加行,为什么 \n 添加空格?
【发布时间】:2020-03-11 22:27:18
【问题描述】:

我正在将数据框打印到文本文件中,并想在顶部添加几行。

import pandas as pd

df = pd.DataFrame(data={'Title': ['Movie1', 'Movie2', 'Movie3', 'Movie4'],
                        'Date': ['2010', '2020', '2009', '2019'],
                        'Names': ['Bob,Jim', 'Jim,Harry,Lou', 'Scott', 'Bill,Jim']})

some_string = "This is my list"
another_string = "It's Fun!"

print(some_string,"\n",another_string,"\n",df, file=open(r'C:path\to\file.txt', 'w' ))

当前输出是这样的:

This is my list 
 It's Fun! 
     Title  Date          Names
0  Movie1  2010        Bob,Jim
1  Movie2  2020  Jim,Harry,Lou
2  Movie3  2009          Scott
3  Movie4  2019       Bill,Jim

我确信这些都是简单的修复,但是:

1) 如何消除使用\n 时出现的右移 1 个字符?

2) 如何删除索引列?我尝试在几个地方添加index=False,但今天早上似乎无法弄清楚。我宁愿在写入(而不是读取)期间删除索引。

【问题讨论】:

  • sep='\n' : print(some_variable, another_variable, df.to_string(index=False), sep='\n', file=open(r'C:path\to\file.txt', 'w' ))

标签: python python-3.x pandas


【解决方案1】:

一个想法是使用+ 将所有字符串连接在一起,对于DataFrame 使用DataFrame.to_string 方法和index=False

print(some_variable + "\n" + another_variable + "\n" + df.to_string(index=False))
This is my list
It's Fun!
  Title  Date          Names
 Movie1  2010        Bob,Jim
 Movie2  2020  Jim,Harry,Lou
 Movie3  2009          Scott
 Movie4  2019       Bill,Jim

评论中的另一个想法 - 参数sep='\',感谢@Chris A:

print(some_variable, another_variable, df.to_string(index=False), sep='\n')

【讨论】:

  • 成功了!我基本上用您的建议重新定义了df,然后简单地将df 打印到文本文件中。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2019-10-23
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
相关资源
最近更新 更多