[英]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.