数据框到file.txt python [英] data frame to file.txt python
问题描述
我有此数据框
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')
推荐答案
这几乎是以下内容:
Python,Pandas:将DataFrame的内容写入文本文件
在这里我再次报告所引用的SO问题的答案,其中很小
您可以使用两种方法。
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.
np.savetxt(),在这种情况下,您应该具有以下内容:
np.savetxt(), in which case you should have something like the following:
np.savetxt('xgboost.txt', a.values, fmt='%d', delimiter="\t", header="X\tY\tZ\tValue")
假设 a
是数据框。当然,您可以更改所需的定界符(制表符,逗号,空格等)。
我附加的答案和@MYGz此处的答案中提到的另一个选项是:使用 to_csv 方法,即:
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_csv method, i.e.:
a.to_csv('xgboost.txt', header=True, index=False, sep='\t', mode='a')
这篇关于数据框到file.txt python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!