-1

I have a pandas dataframe, call it df with 2 columns:

 user_id         result
   ---------      ---------
      12              0
      233             1
      189             0

And so forth. Is there an easy way to write this data frame out to a text file (with column headers removed) that just has comma-separated rows, i.e.,

12, 0
233, 1
189, 0

Thanks.

Thomas Moore
  • 799
  • 1
  • 7
  • 16

5 Answers5

1

use pandas.to_csv function like

df.to_csv("tst.csv")
ansev
  • 26,199
  • 5
  • 10
  • 28
Dev Khadka
  • 4,361
  • 3
  • 16
  • 31
1

df.to_csv("path.txt", header = False, sep = ",", index = False)

This will write it to text file.

secretive
  • 1,700
  • 4
  • 13
0

Try using the pandas to_csv function.

0
 df = df.T.reset_index().T.reset_index(drop=True)
 df.drop(df.index[0], inplace=True)
 df.to_csv('path/to/file/out.csv')

The other solution(s) is very pythonic by comparison!!!

The top line of code is simply wrangling around the problem there is no reset_column function in pandas (ok?). It's not worth explaining because header=False is cleaner

  • thereafter the drop command will remove a row, by default the axis=0 meaning the first row is deleted. So now the header, or rather what was the header, is being deleted
  • to_csv will automatically write the dataframe as a comma separated format, by default

The top line transforms, resets the new row index (no column reset), transforms back resets the row index and blocks 0,1 becoming a header. It's a bit nuts but it works.

M__
  • 590
  • 2
  • 9
  • 22
  • Although this may be a correct answer. One line of code isn't very useful without an explanation of what and how it solves the original question. Please provide details to your answer. – RyanNerd Sep 27 '19 at 22:24
  • Actually, since you pointed it out, it was originally very buggy! Now it just looks horrible – M__ Sep 27 '19 at 23:13
0
df.to_csv("Test.csv",header=False)
GSBYBF
  • 148
  • 3
  • 2
    This may be the correct answer. However one line of code isn't as valuable without an explanation of why this code works and how. Please add details to your answer. – RyanNerd Sep 27 '19 at 22:20
  • 1
    The code is self explanatory, the OP just looks up pandas to_csv – M__ Sep 27 '19 at 22:23