0

I have the pandas data frame. I want to write it in a text file and add text on the top of the frame.

e.g (this is the data.

0   <+000.0 +000.0  +050.0  +000.8>
1   <+000.0 +000.0  +049.1  +000.6>
2   <+000.0 +000.0  +047.6  +000.6>
3   <+000.0 +000.0  +046.5  +000.5>
4   <+000.0 +000.0  +045.3  +000.6>

I want to write it to the file (file.txt) but the following text should be in the file:

#my meas.
#done by me.
#pdd

0   <+000.0 +000.0  +050.0  +000.8>
1   <+000.0 +000.0  +049.1  +000.6>
2   <+000.0 +000.0  +047.6  +000.6>
3   <+000.0 +000.0  +046.5  +000.5>
4   <+000.0 +000.0  +045.3  +000.6>

as I'm new to this, I managed only to create the data frame and write it to a csv file.

Please help.

Omer Ali
  • 11
  • 2
  • this is possible but probably not worth your time/effort to do. Why not just add a separate file with metadata, or do it by hand? – anon01 Oct 11 '20 at 05:57
  • see here: https://stackoverflow.com/questions/56166681/how-to-write-a-pandas-dataframe-to-csv-file-with-custom-header – anon01 Oct 11 '20 at 05:59

1 Answers1

0

You can create a dataframe of the strings you want at the top and then append your main dataframe. Make sure the column names are the same before appending, so that it lines up (0 in my example):

df = pd.DataFrame({0: {0: '<+000.0 +000.0  +050.0  +000.8>',
  1: '<+000.0 +000.0  +049.1  +000.6>',
  2: '<+000.0 +000.0  +047.6  +000.6>',
  3: '<+000.0 +000.0  +046.5  +000.5>',
  4: '<+000.0 +000.0  +045.3  +000.6>'}})
df = pd.DataFrame({0: ['#my meas.', '#done by me.', '#pdd', '']}).append(df)
df.to_csv(header=False, index=False)
df
Out[1]: 
                                 0
0                        #my meas.
1                     #done by me.
2                             #pdd
3
0  <+000.0 +000.0  +050.0  +000.8>
1  <+000.0 +000.0  +049.1  +000.6>
2  <+000.0 +000.0  +047.6  +000.6>
3  <+000.0 +000.0  +046.5  +000.5>
4  <+000.0 +000.0  +045.3  +000.6>
David Erickson
  • 16,433
  • 2
  • 19
  • 35