I see that Pandas has read_fwf
, but does it have something like DataFrame.to_fwf
? I'm looking for support for field width, numerical precision, and string justification. It seems that DataFrame.to_csv
doesn't do this. numpy.savetxt
does, but I wouldn't want to do:
numpy.savetxt('myfile.txt', mydataframe.to_records(), fmt='some format')
That just seems wrong. Your ideas are much appreciated.
Until someone implements this in pandas, you can use the tabulate package:
import pandas as pd
from tabulate import tabulate
def to_fwf(df, fname):
content = tabulate(df.values.tolist(), list(df.columns), tablefmt="plain")
open(fname, "w").write(content)
pd.DataFrame.to_fwf = to_fwf
For custom format for each column you can set format for whole line. fmt param provides formatting for each line
with open('output.dat') as ofile:
fmt = '%.0f %02.0f %4.1f %3.0f %4.0f %4.1f %4.0f %4.1f %4.0f'
np.savetxt(ofile, df.values, fmt=fmt)
Python, Pandas : write content of DataFrame into text File
The question aboves answer helped me. It is not the best, but until to_fwf
exists this will do the trick for me...
np.savetxt(r'c:\data\np.txt', df.values, fmt='%d')
or
np.savetxt(r'c:\data\np.txt', df.values, fmt='%10.5f')
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