Home > database >  How to save a data frame and it's column to a text file?
How to save a data frame and it's column to a text file?

Time:11-22

I have a data frame DF as follows:

import pandas as pd

DF = pd.DataFrame({'A': [1], 'B': [2]})

I'm trying to save it to a Test.txt file by following this answer, with:

np.savetxt(r'Test.txt', DF, fmt='%s')

Which does save only DF values and not the column names:

1 2

How do I save it to have Test.txt with the following contents?

A B
1 2

CodePudding user response:

From the same answer you linked, if you want to use Pandas, just change header=True like:

DF.to_csv('Test.txt', header=True, index=None, sep=' ', mode='a')

If you want to use np.savetxt():

np.savetxt(
    'Test.txt',
    DF.values,
    fmt='%s',
    header=' '.join(DF.columns),
    comments=''
)

Note that I changed the comments parameter to an empty string because the default is to add # in front of the header.

  • Related