21

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')
fedepad
  • 4,509
  • 1
  • 13
  • 27
Amal Kostali Targhi
  • 907
  • 3
  • 11
  • 22

4 Answers4

45

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)
Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78
23

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')
fedepad
  • 4,509
  • 1
  • 13
  • 27
0

Just in case still getting error try this.

np.savetxt("test_file.txt", dataframe.to_numpy(), fmt = "%d")
0

This is another option to save (print) the DataFrame with "nice" format

df.to_string('my_file.txt',index = False)

However, convert it back to DataFrame could get a little tricky depending on the data. But pd.read_fwf('my_file.txt') should work.