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

4 Answers 4

45
+500

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)
Sign up to request clarification or add additional context in comments.

1 Comment

@Amal appending the file name with .txt will save it as a text file. Try it.
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')

1 Comment

Still getting comma in between
0

Just in case still getting error try this.

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.