6

Have a huge pandas dataframe (df) like this:

        id          date      a      b      c
0     0023  201110132120    -30    -45      7
1     0023  201110132130    -30     11   9111
2     0023  201110132140    -24     44    345
3     0023  201110132150    -19    223     11
4     0023  201110132200    -23  -3456  -1250

I need to write this dataframe to a file with special fixed-width for each field. For this i used numpy, f.e.:

np.savetxt('out.txt', df.values, fmt='%+4s %+12s %+5s %+5s %+6s')

That work's fine. Only lost header in this case. Is there a workaround?

I tested it also with pandas to_string function:

df.to_string()

But it is so slow. Why? Are there other options?

2 Answers 2

2

One option is to abuse header option in savetxt:

formats = '%+4s %+12s %+5s %+5s %+6s'

headers = [format(str(x),y.replace('%+','>')) 
              for x, y in zip(df.columns,formats.split())]

np.savetxt('out.txt', df.values, fmt=formats,
           header=' '.join(headers), comments='')
Sign up to request clarification or add additional context in comments.

Comments

1
header='{:>4s} {:>12s} {:>5s} {:>5s} {:>6s}'.format('id','date','a','b','d')
np.savetxt('out.txt', df.values, fmt='%+4s %+12s %+5s %+5s %+6s', header=header)

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.