data frame to file.txt python

Question

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')

Show source
| python   | text   | numpy   | pandas   | dataframe   2017-01-02 15:01 2 Answers

Answers ( 2 )

  1. 2017-01-02 15:01

    CSV means Comma Separated Values. It is plain text (ansi).

    But 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)
    
  2. 2017-01-06 22:01

    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')
    
◀ Go back