[英]write a Pandas dataframe to a .txt file
我的代码写了一个包含大量数据的txt文件。 我正在尝试将熊猫数据帧作为该代码的一部分打印到该txt文件中,但是不能使用.write(),因为它仅接受字符串。
如何获取以DF1为例存储的熊猫数据框,并将其打印在文件中?
我见过类似的问题,但这些问题旨在仅为数据框创建一个txt文件,我希望我的数据框出现在txt文件中
使用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
Pandas DataFrame具有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方法将其选中,以此类推,等等,还可以参见上面的docs链接。
在OP评论附加之前,我最初写了一个关于json的示例。 json
支持dump()
方法来帮助写入文件。 但是,在大多数情况下,它不是将输出附加到vs. csv或txt的最理想的格式。 如果它对任何人有用:
import json
filename = 'file.json'
with open(filename, 'w') as file:
json.dump(df1.to_json(), file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.