data frame to file.txt python
CSV means Comma Separated Values. It is plain text (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.
You don't have to use np.savetxt()
. You can achieve it with df_object.to_csv()
Do it like this:
df_object.to_csv('xgboost.txt', sep='\t', index=False)
This is an almost exact duplicate of the following:
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.
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")
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')