将Pandas数据框写入.txt文件 [英] write a Pandas dataframe to a .txt file
问题描述
我的代码写了一个包含大量数据的txt文件.我正在尝试将熊猫数据框作为该代码的一部分打印到该txt文件中,但是不能使用.write(),因为它仅接受字符串.
My code writes a txt file with lots of data. I'm trying to print a pandas dataframe into that txt file as part of my code but can't use .write() as that only accepts strings.
如何获取以DF1为例存储的熊猫数据框并将其打印在文件中?
How do I take a pandas dataframe, stored as DF1 for example, and print it in the file?
我也看到过类似的问题,但是这些问题旨在仅为数据框创建一个txt文件,我希望我的数据框出现在txt文件中
I've seen similar questions but those are aimed at creating a txt file solely for the dataframe, I would just like my dataframe to appear in a txt file
推荐答案
使用to_string
方法,然后您可以在模式设置为append
('a'
)
use the to_string
method, and then you can use write
with the mode set to append
('a'
)
tfile = open('test.txt', 'a')
tfile.write(df.to_string())
tfile.close()
样本数据
Sample Data
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
Output: 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数据框写入.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!