0

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
accdias
  • 5,160
  • 3
  • 19
  • 31
TourEiffel
  • 4,034
  • 2
  • 16
  • 45
  • 2
    What you're showing is a numPy array and not a dataframe. If youre actually using a pandas DataFrame somewhere, you use df.to_csv -> `https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html` – that_data_guy Nov 21 '22 at 15:45
  • 1
    From the same answer you linked, change `header=True` in the Pandas solution. – m13op22 Nov 21 '22 at 15:53

1 Answers1

1

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.

accdias
  • 5,160
  • 3
  • 19
  • 31
m13op22
  • 2,168
  • 2
  • 16
  • 35