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')
Method 1: Using read_csv()We will read the text file with pandas using the read_csv() function. Along with the text file, we also pass separator as a single space (' ') for the space character because, for text files, the space character will separate each field.
If you want to change the data type for all columns in the DataFrame to the string type, you can use df. applymap(str) or df.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With