数据框到file.txt python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41428539/
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
data frame to file.txt python
提问by Amal Kostali Targhi
I have this 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 save it as a text file with this format
我想将它保存为这种格式的文本文件
X Y Z Value
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
I tried this code but is not working:
我试过这段代码,但没有用:
np.savetxt('xgboost.txt', a.values, delimiter ='\t')
TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e %.18e %.18e')
回答by MYGz
CSVmeans Comma Separated Values. It is plain text (ansi).
CSV表示逗号分隔值。它是纯文本 (ansi)。
TXT is not really a file format, and it could mean multiple things in different contexts. Generally you export tables in either CSV (comma separated values) or TSV (tab separated values). Which you should choose depends mainly on your data: if your data has commas in it but not tabs, you should go for TSV.
TXT 并不是真正的文件格式,它在不同的上下文中可能意味着多种含义。通常,您以 CSV(逗号分隔值)或 TSV(制表符分隔值)格式导出表格。您应该选择哪个主要取决于您的数据:如果您的数据中有逗号但没有制表符,您应该选择 TSV。
You don't have to use np.savetxt()
. You can achieve it with df_object.to_csv()
您不必使用np.savetxt()
. 你可以用df_object.to_csv()
Do it like this:
像这样做:
df_object.to_csv('xgboost.txt', sep='\t', index=False)
回答by fedepad
This is an almost exact duplicate of the following:
Python, Pandas : write content of DataFrame into text File
这是以下内容的几乎完全相同的副本:
Python, Pandas : write content of DataFrame into text File
I report again here the answer from the cited SO question with some very small modifications to fit this case.
You can use two methods.
我在这里再次报告引用的 SO 问题的答案,并进行了一些非常小的修改以适应这种情况。
您可以使用两种方法。
np.savetxt()
, in which case you should have something like the following:
np.savetxt()
,在这种情况下,您应该具有以下内容:
np.savetxt('xgboost.txt', a.values, fmt='%d', delimiter="\t", header="X\tY\tZ\tValue")
assuming a
is the dataframe. Of course you can change the delimiter you want (tab, comma, space,etc.).
The other option, as mentioned in the answer I attached and in the answer here from @MYGz, is to use the to_csvmethod, i.e.:
假设a
是数据帧。当然,您可以更改所需的分隔符(制表符、逗号、空格等)。
另一种选择,如我所附的答案和@MYGz 的答案中所述,是使用to_csv方法,即:
a.to_csv('xgboost.txt', header=True, index=False, sep='\t', mode='a')