Python,Pandas:将 DataFrame 的内容写入文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31247198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python, Pandas : write content of DataFrame into text File
提问by Sounak
I have pandas DataFrame like this
我有这样的 Pandas DataFrame
X Y Z Value
0 18 55 1 70
1 18 55 2 67
2 18 57 2 75
3 18 58 1 35
4 19 54 2 70
I want to write this data to a text file that looks like this:
我想将此数据写入如下所示的文本文件:
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
I have tried something like
我试过类似的东西
f = open(writePath, 'a')
f.writelines(['\n', str(data['X']), ' ', str(data['Y']), ' ', str(data['Z']), ' ', str(data['Value'])])
f.close()
but it's not working. How to do this?
但它不起作用。这该怎么做?
采纳答案by EdChum
You can just use np.savetxt
and access the np attribute .values
:
您可以只使用np.savetxt
和访问 np 属性.values
:
np.savetxt(r'c:\data\np.txt', df.values, fmt='%d')
yields:
产量:
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
or to_csv
:
或to_csv
:
df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep=' ', mode='a')
Note for np.savetxt
you'd have to pass a filehandle that has been created with append mode.
请注意,np.savetxt
您必须传递一个使用追加模式创建的文件句柄。
回答by Anzel
You can use pandas.DataFrame.to_csv(), and setting both index
and header
to False
:
您可以使用pandas.DataFrame.to_csv() ,并同时设置index
和header
到False
:
In [97]: print df.to_csv(sep=' ', index=False, header=False)
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
pandas.DataFrame.to_csv
can write to a file directly, for more info you can refer to the docs linked above.
pandas.DataFrame.to_csv
可以直接写入文件,有关更多信息,您可以参考上面链接的文档。
回答by Rene Duchamp
Late to the party: Try this>
聚会迟到:试试这个>
base_filename = 'Values.txt'
with open(os.path.join(WorkingFolder, base_filename),'w') as outfile:
df.to_string(outfile)
#Neatly allocate all columns and rows to a .txt file
回答by johnDanger
The current best way to do this is to use df.to_string()
:
目前最好的方法是使用df.to_string()
:
with open(writePath, 'a') as f:
f.write(df.to_string(header = False, index = False))
Will output the following
将输出以下内容
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
This method also lets you easily choose which columns to print with the columns
attribute and lets you keep the column, index labels if you wish.
此方法还可让您轻松选择要打印的列columns
属性,并允许您保留列、索引标签(如果您愿意)。
回答by Manohar Rana
@AHegde - To get the tab delimited output use separator sep='\t'.
@AHegde - 要获得制表符分隔的输出,请使用分隔符 sep='\t'。
For df.to_csv:
对于 df.to_csv:
df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep='\t', mode='a')
For np.savetxt:
对于 np.savetxt:
np.savetxt(r'c:\data\np.txt', df.values, fmt='%d', delimiter='\t')
回答by Bhaskaran Mani
I used a slightly modified version:
我使用了一个稍微修改的版本:
with open(file_name, 'w', encoding = 'utf-8') as f:
for rec_index, rec in df.iterrows():
f.write(rec['<field>'] + '\n')
I had to write the contents of a dataframe field (that was delimited) as a text file.
我必须将数据框字段(已分隔)的内容写入文本文件。
回答by Bharat Bhushan
Way to get Excel data to text file in tab delimited form. Need to use Pandas as well as xlrd.
以制表符分隔的形式将 Excel 数据获取到文本文件的方法。需要使用 Pandas 以及 xlrd。
import pandas as pd
import xlrd
import os
Path="C:\downloads"
wb = pd.ExcelFile(Path+"\input.xlsx", engine=None)
sheet2 = pd.read_excel(wb, sheet_name="Sheet1")
Excel_Filter=sheet2[sheet2['Name']=='Test']
Excel_Filter.to_excel("C:\downloads\output.xlsx", index=None)
wb2=xlrd.open_workbook(Path+"\output.xlsx")
df=wb2.sheet_by_name("Sheet1")
x=df.nrows
y=df.ncols
for i in range(0,x):
for j in range(0,y):
A=str(df.cell_value(i,j))
f=open(Path+"\emails.txt", "a")
f.write(A+"\t")
f.close()
f=open(Path+"\emails.txt", "a")
f.write("\n")
f.close()
os.remove(Path+"\output.xlsx")
print(Excel_Filter)
We need to first generate the xlsx file with filtered data and then convert the information into a text file.
我们需要先用过滤后的数据生成xlsx文件,然后将信息转换成文本文件。
Depending on requirements, we can use \n \t for loops and type of data we want in the text file.
根据要求,我们可以使用 \n \t 来表示文本文件中所需的循环和数据类型。