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

Question:

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
Asked By: TourEiffel

||

Answers:

in link u shared in question in the marked answer u can find second way to save file (to_csv method)
pay attention to the arguments of this method 😉

Answered By: Paweł Pietraszko

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.

Answered By: m13op22
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.