【问题标题】:write a Pandas dataframe to a .txt file将 Pandas 数据框写入 .txt 文件
【发布时间】:2018-08-13 20:13:43
【问题描述】:

我的代码编写了一个包含大量数据的 txt 文件。我正在尝试将 pandas 数据框作为我的代码的一部分打印到该 txt 文件中,但不能使用 .write() ,因为它只接受字符串。

如何获取例如存储为 DF1 的 pandas 数据帧并将其打印到文件中?

我见过类似的问题,但这些问题的目的是仅为数据框创建一个 txt 文件,我希望我的数据框出现在一个 txt 文件中

【问题讨论】:

  • 我不明白您在研究中发现的内容与您想要实现的内容之间的区别。请说明您在寻找什么。
  • 我目前已经使用 .write() 向现有的 txt 文件写入了很多内容,并希望将数据帧打印到文件中,然后继续添加更多内容。其他方法只为数据框编写单独的txt文件
  • 这可能是一个菜鸟回复,但您是否尝试过简单地将整个 df 转换为 str?

标签: python pandas


【解决方案1】:

使用to_string方法,然后你可以使用write模式设置为append'a'

tfile = open('test.txt', 'a')
tfile.write(df.to_string())
tfile.close()

样本数据

import pandas as pd
import numpy as np

df = pd.DataFrame({'id': np.arange(1,6,1),
                   'val': list('ABCDE')})

test.txt

This line of text was here before.

代码

tfile = open('test.txt', 'a')
tfile.write(df.to_string())
tfile.close()

输出:test.txt

This line of text was here before.
   id val
0   1   A
1   2   B
2   3   C
3   4   D
4   5   E

【讨论】:

  • 如果我不想索引列怎么办?
  • df.to_string(index=False)
【解决方案2】:

Pandas DataFrames 有 to_string()to_json()to_csv() 方法可能对您有帮助,请参阅:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_string.html

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html

将文本文件写入字符串的示例。使用“w”标志写入,使用“a”附加到文件。

example_string = df1.to_string()
output_file = open('file.txt','a')
output_file.write(example_string)
output_file.close()

如果您只想将某些信息放入文本文件中,您可以使用 pandas 或 json 方法来选择它等,并查看上面的文档链接。

在 OP 评论附加之前,我最初写了一个关于 json 的示例。 json 支持 dump() 方法来帮助写入文件。但是,在大多数情况下,它并不是将输出追加到 csv 或 txt 的最理想格式。如果它对任何人有用:

import json 

filename = 'file.json'

with open(filename, 'w') as file:
    json.dump(df1.to_json(), file)

【讨论】:

  • 抱歉编辑了它,我开始回答并在来电时点击提交,回来并用 to_json、to_csv、to_string 完成它:都是字符串格式。 OP 声称的困难是为 .write() 获取数据帧的字符串表示形式
  • 原始问题没有任何关于附加的内容,这是后来的评论。我修改为放置'a'并描述'w'和'a'标志之间的区别。我可以再次返回并重新排序,以便首先描述 txt LOL
  • 如果我不想索引列怎么办?
  • 尝试:df.to_string(index=False)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-19
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
相关资源
最近更新 更多