I have pandas DataFrame like this
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 write this data to a text file that looks like this:
18 55 1 70 18 55 2 67 18 57 2 75 18 58 1 35 19 54 2 70
I have tried something like
f = open(writePath, 'a') f.writelines(['\n', str(data['X']), ' ', str(data['Y']), ' ', str(data['Z']), ' ', str(data['Value'])]) f.close()
but it's not working. How to do this?
By using pandas. DataFrame. to_csv() method you can write/save/export a pandas DataFrame to CSV File. By default to_csv() method export DataFrame to a CSV file with comma delimiter and row index as the first column.
We can read data from a text file using read_table() in pandas. This function reads a general delimited file to a DataFrame object. This function is essentially the same as the read_csv() function but with the delimiter = '\t', instead of a comma by default.
Pandas DataFrames have to_string (), to_json () and to_csv () methods that may be helpful to you, see: Example of writing a text file to a string. Use 'w' flag to write and 'a' to append to a file. example_string = df1.to_string () output_file = open ('file.txt','a') output_file.write (example_string) output_file.close ()
We are going to use an inbuilt python pandas function Pandas library has a built-in read_csv () method to read a CSV that is a comma-separated value text file so we can use it to read a text file to Dataframe. It read the file at the given path and read its contents in the dataframe.
The default value compression='infer' indicates that Pandas should deduce the compression type from the file extension. You should get the file data.pickle.compress that you can later decompress and read: df again corresponds to the DataFrame with the same data as before.
Pandas is a powerful and flexible Python package that allows you to work with labeled and time series data. It also provides statistics methods, enables plotting, and more. One crucial feature of Pandas is its ability to write and read Excel, CSV, and many other types of files.
You can just use np.savetxt
and access the np attribute .values
:
np.savetxt(r'c:\data\np.txt', df.values, fmt='%d')
yields:
18 55 1 70 18 55 2 67 18 57 2 75 18 58 1 35 19 54 2 70
or to_csv
:
df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep=' ', mode='a')
Note for np.savetxt
you'd have to pass a filehandle that has been created with append mode.
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