Data frame in python file.txt

I have this data file

XYZ 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 in this format

  XYZ 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 did not work:

 np.savetxt('xgboost.txt', a.values, delimiter ='\t') TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e %.18e %.18e') 
+6
source share
2 answers

This is an almost exact duplicate:
Python, Pandas: write the contents of a DataFrame to a text file

I am again reporting the answer from the quoted SO question with some very small changes 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 a data frame. Of course, you can change the delimiter you want (tab, comma, space, etc.).
Another option 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') 
+5
source

CSV stands for comma separated values. This is plain text (ansi).

TXT is not really a file format, and this can mean several things in different contexts. Typically, you export tables to CSV (comma separated values) or TSV (tab separated values). The choice you should choose depends mainly on your data: if your data contains commas, not tabs, you should switch to TSV.

You do not need to use np.savetxt() . You can achieve this with df_object.to_csv()

Do it like this:

 df_object.to_csv('xgboost.txt', sep='\t', index=False) 
+10
source

Source: https://habr.com/ru/post/1013705/


All Articles